In order to use Goolge’s Geocode REST API to retrieve geolocation information, you need to pass a properly encoded URL to https://maps.googleapis.com/maps/api/geocode/json?address=.

For example, to obtain the latitude and longitude of the CNA Building in Chicago, the URL would need to be encoded as follows:

https://maps.googleapis.com/maps/api/geocode/json?address=333+South+Wabash+Chicago+IL



We can encapsulate the logic necessary to retrieve geolocation information within a single Python function: It takes as an argument the address as a string, and returns a dict corresponding to the address’s latitude and longitude:

import requests
import re


def get_geoloc(address: str) -> dict:
    """
    Encode URL with address and pass to Geocode API
    to retrieve corresponding geolocation.
    """
    address_base    = "https://maps.googleapis.com/maps/api/geocode/json?address="
    encoded_address = re.sub("\s+", "+", address.strip()).replace(",", "")
    encoded_url     = address_base + encoded_address

    response = requests.get(encoded_url)
    coords   = response.json()['results'][0]['geometry']['location']
    return(coords)


# usage example =>
>>> get_geoloc("333 S. Wabash Chicago Illinois")
{'lat': 41.877431, 'lng': -87.62565649999999}


This method of geolocation retrieval is sufficient for a relatively small number of lookups in a given day. For applications requesting more than a few thousand address lookups daily, refer to Google’s Geolocation API pricing schedule.

Until next time, happy coding!