How to use the Google Maps API in Python

Quick guide on using Python with the Google Maps API. Learn how to get your API key, and use the Geocoding and Distance Matrix APIs.

This quickstart guide will give you an overview of how to use Python with the Google Maps API and immediately give you access to a wide range of functionalities, such as converting addresses to geographical coordinates and calculating travel distance and time between locations.

How to use the Google Maps API with Python

Before you begin, make sure you have a Google account and Python installed on your system. Some Python libraries, such as requests, might also be required for making API calls.

You might also find it useful to read our comprehensive guide on Python and APIs. It will teach you how to interact with APIs using Python, about Requests, and common HTTP methods. It also addresses advanced techniques and troubleshooting.

Extract Google Maps data with a simple UI or access Google Maps Scraper programmatically from your own Python applications by using the Apify API.

Get $5 of monthly credit and try for free

To work with the Google Maps API, you first need to get an API key. To get this, log in to the Google Cloud Console. Then click on search to find the following Google Maps APIs: Geocoding API and Distance Matrix API.

The Geocoding API is used to convert between addresses and geographic coordinates, and the Distance Matrix API retrieves information about travel time and distance for multiple destinations.

Click on the APIs & Services menu item in the top left navigation bar -> Enable APIs and Services -> Credentials -> Create Credentials -> API Key -> Copy the API key.

Now, let's take a look at retrieving the latitude and longitude of the address. The Geocoding API will help us to get the coordinates.

import requests


def get_lati_longi(api_key, address):

   

    url = 'https://maps.googleapis.com/maps/api/geocode/json'

   

    params = {

        "address": address,

        "key": api_key

    }


    response = requests.get(url, params=params)


    if response.status_code == 200:

        data = response.json()

        if data["status"] == "OK":

            location = data["results"][0]["geometry"]["location"]

            lat = location["lat"]

            lng = location["lng"]

            return lat, lng

        else:

            print(f"Error: {data['error_message']}")

            return 0, 0

    else:

        print("Failed to make the request.")

        return 0, 0


api_key = "YOUR API KEY"

address = 'Vodickova 704/36, 11000 Prague 1, Czech Republic'


lati, longi = get_lati_longi(api_key, address)

print(f"Latitude: {lati}")

print(f"Longitude: {longi}")


The code output should look like this:

Latitude: 50.08138847866026

Longitude: 14.425403029872987

Similarly, you can get information about the drive time and distance between locations using the Distance Matrix API.

import requests


def get_dist_dur(api_key, start, end):

    base_url = "https://maps.googleapis.com/maps/api/distancematrix/json"

    params = {

        "origins": start,

        "destinations": end,

        "key": api_key

    }


    response = requests.get(base_url, params=params)


    if response.status_code == 200:

        data = response.json()

        if data["status"] == "OK":

            distance = data["rows"][0]["elements"][0]["distance"]["text"]

            duration = data["rows"][0]["elements"][0]["duration"]["text"]

            return distance, duration

        else:

            print("Request failed.")

            return None, None

    else:

        print("Failed to make the request.")

        return None, None



api_key = "YOUR API KEY"

start = "Palace Lucerna, Nové Město"

end = "Project FOX, Praha 3-Žižkov"


distance, duration = get_dist_dur(api_key, start, end)

if distance and duration:

    print(f"Driving Distance: {distance}")

    print(f"Driving Duration: {duration}")


Here’s the code output:

Driving Distance: 6.7 km
Driving Duration: 23 min

Next steps with the Google Maps API

That short intro should have given you a good starting point for using Python with the Google Maps API. It's just the tip of the iceberg. There's a whole world of geospatial functionalities and APIs out there to explore. You might like to explore generating static maps with the Maps Static API or identifying local landmarks with the Places API.

If you run into limits with the Google Maps API, you might like to check out our step-by-step guide to scraping places, reviews, popular times, images, and more from Google Maps.

Web scraping gives you the ability to interact with the Google Maps API without limits or restrictions and get the exact data you want.

If you're already familiar with our Google Maps Scraper, you might find some handy tips in our Google Maps scraping manual.

Pythonistas getting into scraping should also look at web scraping with Python or with Beautiful Soup and Requests. Or check out the best Python web scraping libraries.

On this page

Build the scraper you want

No credit card required

Start building