Search code examples
pythonrandomcoordinatespolygon

Generate random coordinates in different polygons


I'm new into Python. I want to generate random coordinates inside a set of polygons.

To generate random coordinates inside one Polygon I found this code on Stackoverflor, which works:

def polygon_random_points (poly, num_points):
    minx, miny, maxx, maxy = poly.bounds 
    while len(points) < num_points:
        random_point = Point([random.uniform(minx, maxx), random.uniform(miny, maxy)])
        if (random_point.within(poly)):
            points.append(random_point)
    return points

But now I struggle to achieve a for loop for all of my polygons. They have this data type: geopandas.geoseries.GeoSeries. Alle_Polygone

I tried this code:

for Standorte in Alle_Polygone:
    def Zufallskoordinaten (poly, Anzahl):
        min_x, min_y, max_x, max_y = poly.bounds
        while len(Punkte) < Anzahl:
            Zufallspunkt = Point([random.uniform(min_x, max_x), random.uniform(min_y, max_y)])
            if (Zufallspunkt.within(poly)):
                Punkte.append(Zufallspunkt)
        return Punkte
Punkte = Zufallskoordinaten(Alle_Polygone,3)

Unfortunately this results in this AttributeError: 'list' object has no attribute 'bounds'.

Maybe someone can help me.


Solution

  • According to the same StackExchange thread where you found your code, there exists a function object.representative_point(), which:

    Returns a cheaply computed point that is guaranteed to be within the geometric object.

    Why reinvent the wheel? Whatever shapely has implemented behind the scenes is guaranteed to be much more efficient than endlessly looping until you happen to pick n-points that satisfy your criteria.

    def get_random_points(polygon, num_points):
        return [polygon.representative_point() for _ in range(num_points)]
    
    def main():
        all_polygons = [...]
        all_points = []
        points_per_polygon = 3
        for polyon in all_polygons:
            all_points.append(get_random_points(polygon, points_per_polygon))
        print(all_points)
    
    main()