How can I get thousands of geographic coordinates (long/lat) randomly generated that remains within a specific country ?
It's for an application i'm doing and i need test data. I preffer it in JSON format.
I have developed a library that should do the trick: PyCristoforo. You can easily install it via pip: pip install pycristoforo
. The only input variables it expects are the country name (or country code) and the number of point you want.
Check it out my Github for further details.
Currently, two main versions are available on PyPi:
Version 1
# getting min, max lat/lng
min_lng = get_min_lng(shape)
min_lat = get_min_lat(shape)
max_lng = get_max_lng(shape)
max_lat = get_max_lat(shape)
# generate random float between [min_lng, max_lng)
val1 = numpy_random.uniform(min_lng, max_lng)
# generate random float between [min_lat, max_lat)
val2 = numpy_random.uniform(min_lat, max_lat)
# random point generation
while counter != points:
if random_point.within(shape):
...
list_of_points.append(ran_point)
counter += 1
Version 2 Version 2 is 20% more faster since it throws away less points:
The first part of the algorithm implements the rejection sampling method (as explained here https://codereview.stackexchange.com/questions/69833/generate-sample-coordinates-inside-a-polygon). The hard constraint about this solution is that is works only for convex shapes. As you may see from the picture below some points can be generated outside the country shape.
To correct it, all the points are then checked if lying inside the country shape. For each point outside the country, a new one is generated.
Hope this was clear enough. Check it out the code and the github repo for further details
Download country polygon from OpenstreetMap or better draw one yourself using google kml, or a free GIS Tool like QGIS. Import the kml in QGIs and export as csv having just lat,lon coordinates Finally you have a list of point in lat,long WGS84
Determine min, max values of country polygon, this gives a rectangular bounding box around the country with lower left corner minLong, minLat.
Create a random longitude valu in range minLongitude, maxLongitude, and a ramdom latitdue value.
Check if random lat, lon isInsidePolygon from step 1, if yes use this value and continue with step 3.
This should give an equal distribution of the random coordiantes within the country (polygon) area.
Notes: Step 4 will not work (easily) for countries that overlapp the datum limit jump from -180 to 180 longitude. But this is usually no limitation.
Edit: To make the task easier, just use a rectangular part within the country, which coordinate you can manually get by using google maps or earth, and start with step 3. That way you will not get points near the country border but it is much easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With