Python Geocoding Tutorial

Before we dive in to the tutorial ...

This is a tutorial for using the OpenCage Geocoding API in Python. Before you can query the API you will need to sign up for an OpenCage API key.

Once you've done that we recommend you spend five minutes on:

Ok, ready?

Install the OpenCage Python module

Compatible with Python version 2, 3 and pypy.

pip install opencage

Geocode coordinate

from opencage.geocoder import OpenCageGeocode
from pprint import pprint

key = 'YOUR-API-KEY'
geocoder = OpenCageGeocode(key)

results = geocoder.reverse_geocode(44.8303087, -0.5761911)
pprint(results)
# [{'components': {'city': 'Bordeaux',
#                  'country': 'France',
#                  'country_code': 'fr',
#                  'county': 'Bordeaux',
#                  'house_number': '11',
#                  'political_union': 'European Union',
#                  'postcode': '33800',
#                  'road': 'Rue Sauteyron',
#                  'state': 'New Aquitaine',
#                  'suburb': 'Bordeaux Sud'},
#   'formatted': '11 Rue Sauteyron, 33800 Bordeaux, France',
#   'geometry': {'lat': 44.8303087, 'lng': -0.5761911}}]

Set output language, error handling

from opencage.geocoder import OpenCageGeocode
from opencage.geocoder import InvalidInputError, RateLimitExceededError, UnknownError

key = 'YOUR-API-KEY'
geocoder = OpenCageGeocode(key)

try:
  results = geocoder.reverse_geocode(44.8303087, -0.5761911, language='de', no_annotation='1')
  if results and len(results):
    print(results[0]['formatted'])
    # 11 Rue Sauteyron, 33800 Bordeaux, Frankreich
except RateLimitExceededError as ex:
  print(ex)
  # Your rate limit has expired. It will reset to 2500 on 2018-10-08T00:00:00
  # Upgrade on https://opencagedata.com/pricing

Lookup coordinates from postal address

from opencage.geocoder import OpenCageGeocode

key = 'YOUR-API-KEY'
geocoder = OpenCageGeocode(key)

query = u'Bosutska ulica 10, Trnje, Zagreb, Croatia'
results = geocoder.geocode(query)

print(u'%f;%f;%s;%s' % (results[0]['geometry']['lat'], 
                        results[0]['geometry']['lng'],
                        results[0]['components']['country_code'],
                        results[0]['annotations']['timezone']['name']))
# 45.797095;15.982453;hr;Europe/Belgrade

Batch geocode a file

Create a file containing addresses
Madrid,Spain
Milan,Italy
Berlin,Germany
import sys
from opencage.geocoder import OpenCageGeocode

key = 'YOUR-API-KEY'
geocoder = OpenCageGeocode(key)
addressfile = 'addresses.txt'

try: 
  with open(addressfile,'r') as f:
    for line in f:
      address = line.strip()
      result = geocoder.geocode(address)

      if result and len(result):
        longitude = result[0]['geometry']['lng']
        latitude  = result[0]['geometry']['lat']
        print(u'%f;%f;%s' % (latitude, longitude, address))
        # 40.416705;-3.703582;Madrid,Spain
        # 45.466797;9.190498;Milan,Italy
        # 52.517037;13.388860;Berlin,Germany
      else:
        sys.stderr.write("not found: %s\n" % address)
except IOError:
  print('Error: File %s does not appear to exist.' % addressfile)
except RateLimitExceededError as ex:
  print(ex)
  # Your rate limit has expired. It will reset to 2500 at midnight UTC timezone
  # Upgrade on https://opencagedata.com/pricing


Alternative Python modules

You can also access the OpenCage geocoder via Denis Carriere's geocoder library. Here is a code sample showing how to query our API using python geocoder.
Start your free trial

2,500 API requests per day.

No credit card required.