When using the following code I get a lot of data but I only want to store lat, long as one string.
It looked like a dictionary and I tried to access it like one: strtLoc['location']
but just got an index must be int error. When I tried indexing there is only one entry and len(strtLoc)
returns 1. In javascript I've seen something like strtLoc.location but I can't figure out how to get only lat and long in python.
Python code:
strtLoc = gmaps.geocode( address=startP)
results:
[{'types': ['locality', 'political'], 'formatted_address': 'New York, NY, USA', 'address_components': [{'long_name': 'New York', 'types': ['locality', 'political'], 'short_name': 'New York'}, {'long_name': 'New York', 'types': ['administrative_area_level_1', 'political'], 'short_name': 'NY'}, {'long_name': 'United States', 'types': ['country', 'political'], 'short_name': 'US'}], 'geometry': {'viewport': {'southwest': {'lat': 40.4773991, 'lng': -74.25908989999999}, 'northeast': {'lat': 40.9175771, 'lng': -73.70027209999999}}, 'location_type': 'APPROXIMATE', 'bounds': {'southwest': {'lat': 40.4773991, 'lng': -74.25908989999999}, 'northeast': {'lat': 40.9175771, 'lng': -73.70027209999999}}, 'location': {'lat': 40.7127837, 'lng': -74.0059413}}, 'place_id': 'ChIJOwg_06VPwokRYv534QaPC8g', 'partial_match': True}]
The problem is that the API returns a list containing a single element, so you can access that with strtLoc = strtLoc[0]
. Then you can access the lat and lng properties under the location key.
strtLoc = strtLoc[0]
location = strtLoc['geometry']['location']
lat = location['lat']
lng = location['lng']
If you want it as a single string, you can join them with a comma using str.join()
location = ','.join([str(lat), str(lng)])