pythonpython-3.xkmlgeogeography

How to draw random points from KML Multigeometry or at least Polygons?


I would like to draw random coordinates inside KML countries shapes made from Multigeometry & Polygons. I tried to get random points of states from different online APIs, such as 3geonames, but they sometimes do not coincide with KML boundaries especially for island states that fails the initialisation of my phylogeographic analysis.

The task of finding internal points inside the figure contour is trivial. So I do not want to reinvent the wheel & am sure that there should be any good way to do this in python directly from kml?


Solution

  • I have not discovered a prepared solutions that is strange for me. Nonetheless, there are some convenient ways to work with geodata in KML using geopandas & shapely.

    gpd.io.file.fiona.drvsupport.supported_drivers['KML'] = 'rw'
    
    some_map = gpd.read_file(fr'some_map.kml', driver='KML')
    
    def getRandomPoint(map: gpd.geodataframe.GeoDataFrame) -> Tuple[float, float]:
        
        def generateRandomPointOfBox() -> shapely.geometry.point.Point:
            return Point(uniform(minx, maxx), uniform(miny, maxy))
        
        minx, miny, maxx, maxy = map.bounds.values[0]
        point = generateRandomPointOfBox()
        while not map.contains(point).values:
            point = generateRandomPointOfBox()
        return (point.x, point.y)
    

    As a result, we can see that this works:

    points = gpd.GeoSeries([Point(getRandomPoint(some_map)) for _ in range(300)])
    points.plot(ax=some_map.plot(), color="red", markersize=4)
    

    enter image description here