Get a google map image of specified location using Google Static Maps API in Python


Google provides a static maps API that returns a map image on our HTTP request. We can directly request for a map image with different parameters based on our need.

We have to create a billing account on Google to use this API. You can go to the website for more details.

Let's see the steps to get the image of a location.

  • Import the requests module.

  • Initialise your API Key and base URL ("https://maps.googleapis.com/maps/api/staticmap?").

  • Initialize the city and zoom value.

  • Update the URL with API Key, City, and Zoom value.

  • USend an HTTP request. And write the response to a file for saving the image.pdate the URL with API Key, City, and Zoom value.

Example

Let's convert the above steps to code.

# importing the module import requests
# base URL BASE_URL = "https://maps.googleapis.com/maps/api/staticmap?"
# API key API_KEY = "Your API Key"
# city CITY = "Hyderabad"
# zoom value
ZOOM = 14
# updating the URL
URL = BASE_URL + "center=" + CITY + "&zoom=" + str(ZOOM) + "&size = 500x500&key=" + API_KEY
# HTTP request
response = requests.get(URL)
# storing the response in a file (image)
with open('hyderabad.png', 'wb') as file:
   # writing data into the file
   file.write(response.content)
# make sure you have a valid API Key
# You will get 403 as status_code if your API Key is invalid

Output

We will get image as below if the HTTP request is success.


Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 12-Feb-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements