While fooling around with the awesome GeoDjango framework, I was looking for a way to generate a random point within a multipolygon.
Justin Bronn (djangopeople.net/jbronn/), the lead developer of GeoDjango was kind enough to point me in the right direction. I thought I share the concept here as it might be helpful to someone:
Define the function:
def get_random_point(extent):
xrange = extent[2] - extent[0]
yrange = extent[3] - extent[1]
randx = xrange * random.random() + extent[0]
randy = yrange * random.random() + extent[1]
return Point(randx, randy)
And then:
extent = mpoly.extent
pnt = get_random_point(extent)
while not mpoly.contains(pnt):
pnt = get_randomPoint(extent)
Let me know what you think or if you’ve got any improvements!
Discussion
No comments for “GeoDjango: getting a random point within a multipolygon”
Post a comment