Search code examples
pythongispostgisgeocodinggeodjango

Generating Random Cordinates for Specific Country


Am Trying to Generate Random Coordinates for a Country

I used this library Faker

def geo_point():
    """make random cordinates"""
    faker = factory.Faker('local_latlng', country_code = 'IN')
    coords = faker.generate()
    return (coords[1], coords[0])

But the problem in this is, it has a very limited set of coordinates around 30-40 we require at least 10,000 for testing.

I tried a simple approach

def random_geo_cordinate():
    """make random geocordinates"""
    x, y = uniform(-180,180), uniform(-90, 90)
    return (y, x)

But then only 10-20 coordinates for Specific Country Comes.

There were a lot of references I found that through shape_files we can generate but in all of them only geom parameters are only available.

I found a method through which I can check that these coordinates lie in that country or not via the Geom column.

But am still missing something in generating random coordinates for a country.

Is there any simple and direct approach.

Am using

POST GIS Database
GeoDjango Server

Note:

  1. I used GDAL for getting shapefiles for a country

Solution

  • You could use Overpass API, which queries the OSM database, so you get real coordinates.
    For example fetching all villages in India:

    import requests
    import json
    
    overpass_url = "http://overpass-api.de/api/interpreter"
    overpass_query = """
    [out:json];area[name="India"];(node[place="village"](area););out;
    """
    
    response = requests.get(
        overpass_url, 
        params={'data': overpass_query}
    )
    
    coords = []
    if response.status_code == 200:
        data = response.json()
        places = data.get('elements', [])
        for place in places:
            coords.append((place['lat'], place['lon']))
         print ("Got %s village coordinates!" % len(coords))
         print (coords[0])
    else:
         print("Error")
    

    Output:

    Got 102420 village coordinates!
    (9.9436615, 77.8978759)
    

    Note: Overpass API is rate limited, so you should save the all coordinates locally and extract your random set from there!
    Additionally, you can play around with places parameter fetching just cities or towns, or fetch restaurant locations for a specific district, ...