Geocoding with Python

Roberto Solari
2 min readSep 24, 2023

--

In the last year I find myself working extensively with spatial data, addresses, GIS (Geographic Information Systems), and geocoding tools. In this article, I’ll share my experiences and insights on how to utilize the Bing Maps API effectively for geocoding tasks

Geocoding is an essential component of spatial data analysis, allowing us to transform text-based addresses into geographic coordinates (latitude and longitude

In one particularly boring project, I needed to convert a large list of addresses into coordinates. The dataset was massive, consisting of thousands of addresses. Manually geocoding this volume of data was impractical and time-consuming. And obviously there was no way I was going to do this task manually for each address. Had it been even one address to convert, I would rather spend 30 minutes automating the process, than 1 minute to do it manually. This is where the Bing Maps API came to my rescue.

before continuing please read the developer license carefully in case of any changes, you should have 125k API calls available to you:

Before you can use the Bing Maps API for geocoding, you’ll need to obtain an API key. Follow these steps to get your API key:

  1. To get started, go to the Bing Maps Portal
  2. Once logged in, create a new Bing Maps API key by clicking on “My Account” and then “Create or view keys.”
  3. Follow the instructions to create a new API key. Make sure to select the appropriate API type (Bing Maps Geocoding API) and set the usage limits according to your needs.
  4. After creating the API key, you can find it in your account settings. Copy this key as you’ll need it in the Python script below.

Now that you have your API key, let’s see how to use it for geocoding in Python. We’ll be using the geopy library, which provides easy access to various geocoding services, including Bing Maps.

import geopy

API_KEY = "YOUR_API_KEY" # Replace with your Bing Maps API key

geolocator = geopy.geocoders.Bing(API_KEY)

def address_to_coordinates(address):
location = geolocator.geocode(address)
if hasattr(location, 'latitude') and hasattr(location, 'longitude'):
return (location.latitude, location.longitude)
else:
return None

addresses = ["Parco Sempione, Milan, Italy"] # List of addresses to convert
coordinates = [] # List of coordinates results

for address in addresses:
coordinate = address_to_coordinates(address)
coordinates.append(coordinate)

print(coordinates)

Replace "YOUR_API_KEY" with the API key you obtained from the Bing Maps portal. This script initializes the geolocator with your API key and defines a function address_to_coordinates that takes an address as input and returns its coordinates. The script then converts a list of addresses into coordinates and prints the results.

Adjust or modify the code to your liking, for example to read the address list from a CSV file

the code:
robertosolari/geocoding (github.com)

--

--