Python Geocoding Tutorial

Install Python module

Compatible with Python version 2 and 3.

pip install opencage

Geocode an address

from opencage.geocoder import OpenCageGeocode

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

query = "82 Clerkenwell Road, London";
result = geocoder.geocode(query)

Batch geocode a file

import sys
from opencage.geocoder import OpenCageGeocode

key = 'YOUR-API-KEY'
geocoder = OpenCageGeocode(key)
infilepath = 'cities.txt'

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

      if result and len(result):
        longitude = result[0]['geometry']['lng']
        latitude  = result[0]["geometry"]["lat"]
        z = "%f;%f;%s" % (latitude, longitude, query)
        print z
      else:
        sys.stderr.write("not found: %s\n" % query)
except IOError:
  print("Error: File does not appear to exist.")

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.