How To / Python: Get geographic coordinates using Google (Geocode)

Thanks to pygeocoder, obtaining geographic coordinates, or geocoding, from Google is very simple. The Python script below can do that very easily.

from pygeocoder import Geocoder
import pandas as pd

cities = {
'City': ['Coral Gables', 'Hawarden', 'Chapeco', 'Merida', 'Assisi'],
'Nation': ['United States', 'United Kingdom', 'Brazil', 'Spain', 'Italy']}

df = pd.DataFrame(cities)
info = pd.DataFrame([])

for index, row in df.iterrows():

    city = str(row['City'])
    nation = str(row['Nation'])
    location = str(row['City'] + ', ' + row['Nation'])

    result = Geocoder.geocode(location)
    coords = str(result[0].coordinates)

    chars_to_remove = ['(' , ')']
    coords = coords.translate(None, ''.join(chars_to_remove))

    lat = float(coords.split(',')[0])
    long = float(coords.split(',')[1])

    line = pd.Series([city, nation, lat, long])

    info = info.append(line, ignore_index = True)

In line 15 I create the ‘address’ I want to geocode. The format is ‘City, Country’. In line 17, I use pygeocoder to obtain the coordinates. In lines 18-24, I get the values of the latitude and longitude by splitting the result of the geocoder.

The result is a list of cities with their respective latitude and longitude.

Coral Gables, United States, 25.721490, -80.268384
Hawarden, United Kingdom, 53.185690, -3.029807
Chapeco, Brazil, -27.100934, -52.615699
Merida, Spain, 38.939427, -6.365157
Assisi, Italy, 43.070702, 12.619597

If you are dealing with a large amount of cities, you may want to add a couple of lines in order to deal with exceptions (e.g. when pygeocoder cannot find the city). You could use try and except, replacing the lat and long variables with a specific number very different from the values of a geographic coordinate (not pretty but effective!).

You can check Chris Albon’s website. He goes through more details and I probably borrowed from his code to write this script.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s