Skip to main content
4 of 5
added 90 characters in body

How to generate random coordinates in a multipolygon in python

How to generate random points in multi-polygon using geojson in python ? thus far I found a class in JavaScript named :

randomPointsOnPolygon(numberOfPoints, polygon)

but I need to use something like that in python , my code is like

import json
import geojson

with open('my_city_boundaries.geojson') as f:
    data = json.load(f)

for feature in data['features']:
    if feature['properties']["name:en"] == state_name:
         # I need to generate some coordinates within that state

I tried shapely like this and it didnt work . it doesnt recognize Points attribute

import shapely import Point
import json
import geojson
from osgeo import ogr


def generate_random(number, polygon):
    list_of_points = []
    minx, miny, maxx, maxy = env[0], env[2], env[1], env[3]
    counter = 0
    while counter < number:
        pnt = Point(random.uniform(minx, maxx), random.uniform(miny, maxy))
        if polygon.contains(pnt):
            list_of_points.append(pnt)
            counter += 1
    return list_of_points

with open('ir_states_boundaries_coordinates.geojson') as f:
    data = json.load(f)
print("\n\nName your state from this list\n\n")
for feature in data['features']:  # print a list of valid state names
    print(feature['properties']['name:en'])
state_name = raw_input("\n")
for feature in data['features']:
    if feature['properties']["name:en"] == state_name:
        geom = feature['geometry']
        geom = json.dumps(geom)
        polygon = ogr.CreateGeometryFromJson(geom)
        env = polygon.GetEnvelope()
        result = generate_random(10, polygon)
print result