Given the lat/long coordinates, how can we find out the city/country?
You need geopy
pip install geopy
and then:
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.reverse("48.8588443, 2.2943506")
print(location.address)
to get more information:
print (location.raw)
{'place_id': '24066644', 'osm_id': '2387784956', 'lat': '41.442115', 'lon': '-8.2939909', 'boundingbox': ['41.442015', '41.442215', '-8.2940909', '-8.2938909'], 'address': {'country': 'Portugal', 'suburb': 'Oliveira do Castelo', 'house_number': '99', 'city_district': 'Oliveira do Castelo', 'country_code': 'pt', 'city': 'Oliveira, São Paio e São Sebastião', 'state': 'Norte', 'state_district': 'Ave', 'pedestrian': 'Rua Doutor Avelino Germano', 'postcode': '4800-443', 'county': 'Guimarães'}, 'osm_type': 'node', 'display_name': '99, Rua Doutor Avelino Germano, Oliveira do Castelo, Oliveira, São Paio e São Sebastião, Guimarães, Braga, Ave, Norte, 4800-443, Portugal', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'}
The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.
Try this link to see an example of the output (this is in json, output is also available in XML)
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
Another option:
- Download the cities database from http://download.geonames.org/export/dump/
- Add each city as a lat/long -> City mapping to a spatial index such as an R-Tree (some DBs also have the functionality)
- Use nearest-neighbour search to find the closest city for any given point
Advantages:
- Does not depend on an external server to be available
- Very fast (easily does thousands of lookups per second)
Disadvantages:
- Not automatically up to date
- Requires extra code if you want to distinguish the case where the nearest city is dozens of miles away
- May give weird results near the poles and the international date line (though there aren't any cities in those places anyway