Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 HTTP request. We can directly request for a map image with different parameters based on our needs.
We need to create a billing account on Google to use this API. You can visit the Google Static Maps API documentation for more details on getting an API key.
Prerequisites
Before starting, make sure you have ?
A valid Google Maps API key with Static Maps API enabled
The
requestsmodule installed (pip install requests)
Steps to Get Map Image
Follow these steps to retrieve a Google Maps image ?
Import the requests module
Initialize your API Key and base URL
Set the location and zoom parameters
Construct the complete URL with all parameters
Send HTTP request and save the response as an image file
Example
Here's a complete example that downloads a map image of Hyderabad ?
# importing the module
import requests
# base URL
BASE_URL = "https://maps.googleapis.com/maps/api/staticmap?"
# API key (replace with your actual API key)
API_KEY = "Your_API_Key_Here"
# 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)
# check if request was successful
if response.status_code == 200:
# storing the response in a file (image)
with open('hyderabad.png', 'wb') as file:
# writing data into the file
file.write(response.content)
print("Map image saved successfully!")
else:
print(f"Error: {response.status_code}")
print("Make sure you have a valid API Key")
Parameters Explanation
The Google Static Maps API accepts several parameters ?
| Parameter | Description | Example |
|---|---|---|
center |
Location to center the map | Hyderabad or 17.3850,78.4867 |
zoom |
Zoom level (1-21) | 14 |
size |
Image dimensions | 500x500 |
key |
Your Google Maps API key | AIza... |
Enhanced Example with Error Handling
Here's an improved version with better error handling and customizable parameters ?
import requests
def get_map_image(api_key, location, filename="map.png", zoom=14, size="500x500"):
"""
Download a Google Static Map image for a specified location.
Parameters:
- api_key: Your Google Maps API key
- location: City name or coordinates (lat,lng)
- filename: Name of the output file
- zoom: Zoom level (1-21)
- size: Image size in format "widthxheight"
"""
base_url = "https://maps.googleapis.com/maps/api/staticmap?"
# Construct the URL
url = f"{base_url}center={location}&zoom={zoom}&size={size}&key={api_key}"
try:
# Make HTTP request
response = requests.get(url)
if response.status_code == 200:
# Save the image
with open(filename, 'wb') as file:
file.write(response.content)
print(f"Map image saved as '{filename}'")
return True
else:
print(f"Error {response.status_code}: Failed to get map image")
if response.status_code == 403:
print("Check your API key permissions")
return False
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return False
# Usage example
API_KEY = "Your_API_Key_Here"
get_map_image(API_KEY, "New York", "nyc_map.png", zoom=12)
Output
When the HTTP request is successful, you'll get a PNG image file saved to your current directory. The image will show a satellite/roadmap view of the specified location.
Important Notes
Replace
"Your_API_Key_Here"with your actual Google Maps API keyEnable the Maps Static API in your Google Cloud Console
Status code 403 indicates an invalid or restricted API key
You can use coordinates (latitude, longitude) instead of city names for more precision
Conclusion
Google Static Maps API provides an easy way to programmatically retrieve map images. Remember to handle API errors properly and keep your API key secure when deploying applications.
---