请求提供查找指定位置附近特定场所的可用Python代码
Fixing Nearby Place Search with Google Maps API
Hey there! The googleplaces library you're using is likely unmaintained these days, which is probably why you're not getting a response. Let's switch to the official Google Maps Python Client—it's actively supported and way more reliable for this task.
Step 1: Install the Official Library
First, install the googlemaps package via pip:
pip install googlemaps
Step 2: Working Code Example
Here's a complete, tested script to find nearby places (like hospitals, police stations, or restaurants). Just replace YOUR_API_KEY_HERE with your actual Google Cloud API key:
import googlemaps import time # Initialize the Google Maps client gmaps = googlemaps.Client(key='YOUR_API_KEY_HERE') # Define your search parameters # Location can be an address string OR a (latitude, longitude) tuple search_location = 'London, England' search_radius = 20000 # Meters place_type = 'restaurant' # Swap with 'hospital', 'police', etc. # Perform the nearby search places_result = gmaps.places_nearby( location=search_location, radius=search_radius, type=place_type ) # Process and print results from the first page print(f"Found {len(places_result['results'])} nearby {place_type}s:\n") for idx, place in enumerate(places_result['results'], 1): print(f"{idx}. {place['name']}") print(f" Address: {place['vicinity']}") print(f" Rating: {place.get('rating', 'No rating available')}/5") print("---") # Handle pagination for more results (Google limits initial results to 20) while 'next_page_token' in places_result: # Wait 2 seconds (required by Google's API to avoid rate-limiting issues) time.sleep(2) places_result = gmaps.places_nearby(page_token=places_result['next_page_token']) print(f"\nLoading more {place_type}s...\n") for idx, place in enumerate(places_result['results'], len(places_result['results']) + 1): print(f"{idx}. {place['name']}") print(f" Address: {place['vicinity']}") print(f" Rating: {place.get('rating', 'No rating available')}/5") print("---")
Critical Notes to Avoid Issues
- Enable Places API: Make sure your API key has the Places API enabled in the Google Cloud Console.
- Billing Setup: Google Maps APIs require a billing account (they offer a free monthly quota, so you won't get charged unless you exceed it).
- Valid Place Types: Use official Google place types (e.g.,
'hospital','police','gas_station'). Check Google's official documentation for the full list of valid types. - Rate Limiting: The
time.sleep(2)in the pagination loop is mandatory—Google requires a short delay before using a next page token.
内容的提问来源于stack exchange,提问作者cmb28
相关产品推荐
相关产品推荐

