杰瑞科技汇

Python如何调用Google Maps API?

Of course! Using Google Maps in Python is a very common task, and there are several excellent libraries to help you do it. The right choice depends on what you want to achieve:

  1. Static Maps: For creating simple, non-interactive images of a map (like a snapshot).
  2. Interactive Maps: For creating rich, zoomable, clickable maps directly in your Jupyter Notebook or web app.
  3. Geocoding: Converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (latitude, longitude) and vice-versa.
  4. Directions & Distance: Calculating driving, walking, or transit routes between two points.

Let's break down the most popular libraries for each task.


Prerequisites: Get a Google Maps API Key

Almost all of these libraries require a Google Cloud Platform API Key.

  1. Go to the Google Cloud Console: https://console.cloud.google.com/
  2. Create a New Project (or select an existing one).
  3. Enable the Necessary APIs: For most use cases, you'll need at least one of these:
    • Maps Static API: (for static images)
    • Geocoding API: (for address/coordinate conversion)
    • Directions API: (for routes)
    • Places API: (for searching for businesses, etc.)
  4. Create an API Key:
    • In the left menu, go to "APIs & Services" -> "Credentials".
    • Click "+ CREATE CREDENTIALS" and choose "API key".
    • Copy your new API key. Keep it secure! Do not commit it to public repositories like GitHub.
  5. Restrict Your API Key: It's crucial to restrict your key to only the APIs you're using and to your own IP addresses or referers to prevent unauthorized use.

Static Maps with requests

This is the most basic approach. You construct a special URL with your map parameters and download the resulting image. The requests library is perfect for this.

Use Case: You need a simple image of a map for a report, presentation, or as a static element in a web page.

Library: requests

Example: Plot a marker on a map

import requests
# Your API Key (replace with your own)
API_KEY = "YOUR_API_KEY"
# Location coordinates (e.g., Eiffel Tower)
latitude = 48.858370
longitude = 2.294481
# Construct the URL for the Static Map API
# We add a marker ('markers') and set the zoom ('zoom')
url = f"https://maps.googleapis.com/maps/api/staticmap?center={latitude},{longitude}&zoom=15&size=600x400&markers=color:red%7C{latitude},{longitude}&key={API_KEY}"
# Make the request to the Google API
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
    # Save the image to a file
    with open "map_image.png", "wb") as file:
        file.write(response.content)
    print("Map image saved as map_image.png")
else:
    print(f"Error: {response.status_code}")
    print(response.text)

When you run this, a file named map_image.png will be created in your directory, showing a map of the Eiffel Tower with a red marker.


Interactive Maps with folium

folium is the go-to library for creating beautiful, interactive, HTML-based maps. It's built on top of the powerful Leaflet.js library and is incredibly easy to use in Jupyter Notebooks.

Use Case: Data visualization, dashboards, exploring data points on a map, creating clickable maps.

Library: folium

Installation:

pip install folium

Example: Create an interactive map with markers

import folium
# Define the center of the map (e.g., San Francisco)
sf_map = folium.Map(location=[37.7749, -122.4194], zoom_start=12)
# Add a marker for the Golden Gate Bridge
folium.Marker(
    location=[37.8199, -122.4783],
    popup="<b>Golden Gate Bridge</b>",
    tooltip="Click for more info",
    icon=folium.Icon(color='red', icon='info-sign')
).add_to(sf_map)
# Add a circle marker for Union Square
folium.CircleMarker(
    location=[37.7880, -122.4074],
    radius=50,
    popup="<b>Union Square</b>",
    color='blue',
    fill=True,
    fill_color='blue',
    fill_opacity=0.6
).add_to(sf_map)
# Save the map to an HTML file
sf_map.save("san_francisco_map.html")
# The map will open in your browser if you run this in a Jupyter Notebook
# sf_map

Running this code will create an san_francisco_map.html file. Open it in your web browser to see an interactive map with markers and popups.


Geocoding with geopy

geopy is a fantastic library that provides a common interface for several geocoding services, including Google's. It makes it incredibly simple to convert between addresses and coordinates.

Use Case: Finding the latitude/longitude of an address, or finding the address of a set of coordinates.

Library: geopy

Installation:

pip install geopy

Example: Geocode an address

from geopy.geocoders import GoogleV3
from geopy.exc import GeocoderTimedOut, GeocoderQuotaExceeded
# Your API Key
API_KEY = "YOUR_API_KEY"
# Initialize the geocoder
geolocator = GoogleV3(api_key=API_KEY)
# Address to geocode
address = "1600 Amphitheatre Parkway, Mountain View, CA"
try:
    # Geocode the address
    location = geolocator.geocode(address)
    if location:
        print(f"Address: {location.address}")
        print(f"Latitude: {location.latitude}")
        print(f"Longitude: {location.longitude}")
    else:
        print("Could not find the address.")
except GeocoderQuotaExceeded:
    print("Error: Google Maps API quota exceeded.")
except GeocoderTimedOut:
    print("Error: Geocoding service timed out.")
except Exception as e:
    print(f"An error occurred: {e}")

Directions & Distance with googlemaps

The googlemaps library is a direct, unofficial Python client for the Google Maps APIs. It's very powerful and gives you easy access to the Directions, Distance Matrix, and other services.

Use Case: Calculating routes, getting travel times, finding distances, and getting detailed step-by-step directions.

Library: googlemaps

Installation:

pip install googlemaps

Example: Get driving directions and travel time

import googlemaps
import time
# Your API Key
API_KEY = "YOUR_API_KEY"
# Initialize the client
gmaps = googlemaps.Client(key=API_KEY)
# Define origin and destination
origin = "Sydney Town Hall, Sydney, Australia"
destination = "Parramatta, NSW, Australia"
try:
    # Get directions
    directions_result = gmaps.directions(origin, destination, mode="driving")
    if directions_result:
        # The result is a list of routes, we'll take the first one
        route = directions_result[0]
        leg = route['legs'][0] # The first leg of the journey
        print(f"From: {leg['start_address']}")
        print(f"To: {leg['end_address']}")
        print("-" * 30)
        # Get distance and duration
        distance = leg['distance']['text']
        duration = leg['duration']['text']
        print(f"Distance: {distance}")
        print(f"Duration: {duration}")
        print("-" * 30)
        # Print the first step of the directions
        first_step = leg['steps'][0]
        print("First step:", first_step['html_instructions'])
    else:
        print("Could not find directions.")
except Exception as e:
    print(f"An error occurred: {e}")

Summary: Which Library to Choose?

Task Recommended Library Ease of Use Key Feature
Creating a simple map image requests Very Easy Direct URL-based API calls
Interactive data visualization folium Easy Creates rich, interactive HTML maps
Address/Coordinate conversion geopy Easy Unified interface for many geocoding services
Routes, travel time, distance googlemaps Moderate Direct client for many Google Maps APIs

For most data science and visualization projects in Python, folium and geopy are your best friends. For more complex applications that need routing or detailed place information, googlemaps is the way to go.

分享:
扫描分享到社交APP
上一篇
下一篇