如何从Google Geocoding API返回的Python字典中提取经纬度?
Hey there! Glad you’ve already parsed the API response into a dictionary—you’re most of the way there. Here’s a straightforward way to pull out the latitude and longitude values:
Step-by-Step Extraction
The geocoding response nests location data in this path: results → (first result item) → geometry → location. Since the API returns a list of results (with the first being the most accurate match for your address), we’ll target that first item.
Here’s the code to do it:
# Grab the top matching result from the response top_result = response_data['results'][0] # Navigate to the location coordinates section location_data = top_result['geometry']['location'] # Extract latitude and longitude latitude = location_data['lat'] longitude = location_data['lng'] # Print or use the values as needed print(f"Latitude: {latitude}") print(f"Longitude: {longitude}")
Shortened Version (For Brevity)
If you prefer more concise code, you can condense this into one line:
lat, lng = response_data['results'][0]['geometry']['location'].values()
Critical Pre-Check: Verify API Success
Before extracting data, always confirm the API call worked by checking the status field. This avoids errors if the address couldn’t be geocoded:
if response_data['status'] == 'OK': # Run your extraction code here lat, lng = response_data['results'][0]['geometry']['location'].values() print(f"Coordinates: ({lat}, {lng})") else: print(f"Geocoding failed with status: {response_data['status']}")
This will get you the exact latitude and longitude for the Empire State Building from your provided response.
内容的提问来源于stack exchange,提问作者Adela

