geopy
geopy is a Python client for numerous popular geocoding web services, including OpenStreetMap Nominatim, Google Geocoding API, and Bing Maps. It simplifies the process for Python developers to locate the coordinates of addresses, cities, countries, and landmarks globally, as well as perform reverse geocoding. The library is actively maintained, with its current stable version being 2.4.1, and releases occur regularly to add features and address issues. It supports Python versions 3.7 through 3.12.
Warnings
- breaking The `geopy.distance.vincenty` algorithm was removed in geopy 2.0.0. It should be replaced with `geopy.distance.geodesic` for accurate distance calculations.
- breaking In geopy 2.0.0, the default for the `exactly_one` parameter in geocoders' `geocode` and `reverse` methods changed to `True`. This means methods will return a single `Location` object (or `None`) by default, rather than a list.
- breaking Service-specific request parameters are no longer accepted in the `__init__` methods of geocoder classes as of geopy 2.0.0. They must now be passed directly to the corresponding `geocode` or `reverse` methods.
- breaking The `Algolia Places` geocoder was removed in geopy 2.4.0 because the underlying service was shut down.
- gotcha The `Nominatim` geocoder (OpenStreetMap) requires a `user_agent` string in its constructor to identify your application. Failing to provide one may result in `ConfigurationError` or service blocking.
- gotcha The `GoogleV3` geocoder changed its behavior in geopy 2.1.0: a missing `api_key` now raises an error instead of a warning.
Install
-
pip install geopy
Imports
- Nominatim
from geopy.geocoders import Nominatim
- geodesic
from geopy.distance import geodesic
- Location
from geopy.location import Location
- Point
from geopy.point import Point
Quickstart
import os
from geopy.geocoders import Nominatim
# For Nominatim, a 'user_agent' is required.
# In a production environment, use a unique, descriptive string for your application.
geolocator = Nominatim(user_agent=os.environ.get('GEOPY_USER_AGENT', 'my_geocoding_app'))
# Geocode an address
address = "175 5th Avenue NYC"
location = geolocator.geocode(address)
if location:
print(f"Address: {location.address}")
print(f"Latitude: {location.latitude}, Longitude: {location.longitude}")
else:
print(f"Could not find location for: {address}")
# Reverse geocode coordinates
coordinates = "52.509669, 13.376294" # Berlin
reversed_location = geolocator.reverse(coordinates)
if reversed_location:
print(f"\nCoordinates: {coordinates}")
print(f"Address: {reversed_location.address}")
else:
print(f"Could not find address for: {coordinates}")