I need to convert longitude and latitude coordinates to either country or city, is there an example of this in python?
thanks in advance!
In general the Google API is the best approach. It was not suitable for my case as I had to process a lot of entries and the api is slow.
I coded a small version that does the same but downloads a huge geometry first and computes the countries on the machine.
import requests
from shapely.geometry import mapping, shape
from shapely.prepared import prep
from shapely.geometry import Point
data = requests.get("https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson").json()
countries = {}
for feature in data["features"]:
geom = feature["geometry"]
country = feature["properties"]["ADMIN"]
countries[country] = prep(shape(geom))
print(len(countries))
def get_country(lon, lat):
point = Point(lon, lat)
for country, geom in countries.iteritems():
if geom.contains(point):
return country
return "unknown"
print(get_country(10.0, 47.0))
# Austria