[GIS] Reading GeoJSON file and querying Nominatim

geojsonnominatimpython

I need to loop through a GeoJSON file, where for each "feature", find the city where the track started:

with open('input.geojson') as f:
    gj = geojson.load(f)

for track in gj['features']:
    #OK
    print track['geometry']['coordinates'][0]

    #How to query Nominatim to find the city that lat,lon belongs to?

    #Next step : edit 'name' in gj

with open('dump.geojson', 'w') as f:
   dump(gj, f, indent=2)

Would someone have some code handy?

Best Answer

You can try using Geopy.

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent='my_app')

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

for i, track in enumerate(geojson['features']):
    lat, lon = track['geometry']['coordinates'][0]
    location = geolocator.reverse((lat, lon))
    # full address as returned by Nominatim
    address = location.address
    # city or country
    city = location.raw['address']['city']
    country = location.raw['address']['country']
    # update geojson
    geojson['features'][i]['properties']['name'] = city

with open('dump.geojson', 'w') as f:
    json.dump(geojson, f, indent=True)