Geocoding with Geopy in Python

I have already demonstrated various possibilities for geocoding spatial data in the form of city or location names in R, using APIs such as the one provided by Open Street Map.

In this post I will demonstrate the possibility of geocoding location names in Python, using Geopy. Geopy is a Python module that allows geocoding of strings by providing access to various geocoding services.

Below I import Geopy (supports pip install command) and use it for geocoding a list of city names using the Nominatim service. This is a service based on Open Street Map.

# importing Geopy
import geopy
# get a handler for a Nominatim service object
service = geopy.Nominatim(user_agent = "myGeocoder")
# geocode a city name using the Nominatim (i.e. OSM) service
service.geocode("Berlin, Germany")
Location(Berlin, Deutschland, (52.5170365, 13.3888599, 0.0))

The geocode() function returns a special data type of type location. A location object has various attributes:

# creating another location object by geocoding Berlin city name in Germany using Nominatim service
locationObj = service.geocode("Berlin, Germany")
# latitude
print(locationObj.latitude)
# longitude
print(locationObj.longitude)
52.5170365
13.3888599

Using these latitude and longitude coodinates one could now e.g. place a marker on a map, using the Folium module in Python in combination with Geopy:

# import folium
import folium
# create a base map centered around Berlin
mapObj = folium.Map(location = [locationObj.latitude,locationObj.longitude], zoom_start = 5)
# create marker object for Berlin
markerObj = folium.Marker(location = [locationObj.latitude,locationObj.longitude])
# add marker to map
markerObj.add_to(mapObj)
# display map
mapObj

You May Also Like

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.