This is a tutorial for using the OpenCage Geocoding API in a Python Jupyter Notebook.
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:
Install with pip, compatible with Python version 2 and 3.
% pip install opencage
from opencage.geocoder import OpenCageGeocode
from pprint import pprint
Replace YOUR-API-KEY
below with the OpenCage API key for your account.
key = 'YOUR-API-KEY'
geocoder = OpenCageGeocode(key)
results = geocoder.reverse_geocode(44.8303087, -0.5761911)
pprint(results)
from opencage.geocoder import InvalidInputError, RateLimitExceededError, UnknownError
try:
results = geocoder.reverse_geocode(44.8303087, -0.5761911, language='de', no_annotation='1')
if results and len(results):
print(results[0]['formatted'])
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
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']))
Install ipyleaflet
% pip install ipyleaflet
from ipyleaflet import *
results = geocoder.geocode(u'Brussels, Belgium')
center = (results[0]['geometry']['lat'], results[0]['geometry']['lng'])
map = Map(center=center, zoom=6)
marker = Marker(location=center, draggable=False)
map.add_layer(marker)
map
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.