I tried to find the latitude and longitude of an address through Google Geocoding API.
I got the json string using the following code:
address = "the Empire State Building" api_key = " " #not shown hereurl = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s" % (address,api_key) response = requests.get(url) response_data = response.json()The dictionaryresponse_data is shown as follows.
{'results': [{'address_components': [{'long_name': '20', 'short_name': '20', 'types': ['street_number']}, {'long_name': 'West 34th Street', 'short_name': 'W 34th St', 'types': ['route']}, {'long_name': 'Manhattan', 'short_name': 'Manhattan', 'types': ['political', 'sublocality', 'sublocality_level_1']}, {'long_name': 'New York', 'short_name': 'New York', 'types': ['locality', 'political']}, {'long_name': 'New York County', 'short_name': 'New York County', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'New York', 'short_name': 'NY', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}, {'long_name': '10001', 'short_name': '10001', 'types': ['postal_code']}], 'formatted_address': '20 W 34th St, New York, NY 10001, USA', 'geometry': {'location': {'lat': 40.7484405, 'lng': -73.98566439999999}, 'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 40.7497894802915, 'lng': -73.98431541970848}, 'southwest': {'lat': 40.7470915197085, 'lng': -73.98701338029149}}}, 'place_id': 'ChIJaXQRs6lZwokRY6EFpJnhNNE', 'plus_code': {'compound_code': 'P2X7+9P New York, NY, USA', 'global_code': '87G8P2X7+9P'}, 'types': ['establishment', 'museum', 'point_of_interest', 'tourist_attraction']}], 'status': 'OK'}What next steps should I do to get the latitude and longitude of that address?
1 Answer1
When you runprint(type(response_data)) it returnsdict?
If it is of thedict class, you can usedict methods....Unfortunately, the values you want are in a dictionary in a dictionary in a dictionary in a list in a dictionary.
Long story short, try
latlong = response_data['results'][0]['geometry']['location']print(latlong)Longer explanation:"response_data" is a dict, with 2 keys (your info is stored at 'results').the value of 'results' is a list, 1 entry (your info is at index 0).the value at index 0 is a dict, with 6 keys (your info is at key = 'geometry').the value of 'geometry' is a dict, 3 entries (your info is at key 'location').the value of 'location' is a dict, 2 entries (your info!!! 'lat', 'lng').
Comments
Explore related questions
See similar questions with these tags.
