How to use the Google Maps API in Python
Tags: python, api, googlemaps, tutorial
Published: 2023-12-14 14:24:15

---
title: How to use the Google Maps API in Python
published: true
date: 2023-09-10 22:00:00 UTC
tags: Python, APIs, GoogleMaps, Tutorial
canonical_url: https://blog.apify.com/google-maps-api-python/
---

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 in Python: illustration of futuristic map with red Google Maps pins](https://blog.apify.com/content/images/2023/09/google-maps-api-python-futuristic-map-with-red-pins.jpg)

_Navigating the Google Maps API with Python is easy when you know how_

## **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](https://blog.apify.com/what-is-an-api/).

You might also find it useful to read our [comprehensive guide on Python and APIs](https://blog.apify.com/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.

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](https://cloud.google.com/cloud-console). Then click on search to find the following Google Maps APIs: [Geocoding API](https://console.cloud.google.com/marketplace/details/google/geocoding-backend.googleapis.com) and [Distance Matrix API](https://console.cloud.google.com/marketplace/product/google/distance-matrix-backend.googleapis.com).

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}")
```

Heres 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](https://developers.google.com/maps/documentation/maps-static/overview) or identifying local landmarks with the [Places API](https://developers.google.com/maps/documentation/places/web-service).

![How to use the Google Maps API in Python: Google Maps location pin on street](https://blog.apify.com/content/images/2023/09/google-maps-api-python-location-pin-on-street.jpg)

_Explore a world of possibilities by using the Google Maps API or web scraping to extract Maps data_

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](https://blog.apify.com/step-by-step-guide-to-scraping-google-maps/).

[Web scraping](https://blog.apify.com/what-is-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](https://blog.apify.com/google-maps-scraping-manual/).

Pythonistas getting into scraping should also look at [web scraping with Python](https://blog.apify.com/web-scraping-python/) or with [Beautiful Soup and Requests](https://blog.apify.com/web-scraping-with-beautiful-soup/). Or check out the [best Python web scraping libraries](https://blog.apify.com/what-are-the-best-python-web-scraping-libraries/).