如何从python 3中的谷歌地理编码API获得lat / long?

时间:2016-12-15 21:56:28

标签: python google-maps python-3.x google-maps-api-3 google-geocoder

当使用以下代码时,我获得了大量数据,但我只想存储lat,只要一个字符串。

它看起来像一个字典,我试图像它一样访问它:strtLoc['location']但只是得到一个索引必须是int错误。当我尝试索引时,只有一个条目并且len(strtLoc)返回1.在javascript中我看到过类似strtLoc.location但我无法弄清楚如何在python中只得到lat和long。

Python代码: strtLoc = gmaps.geocode( address=startP)

结果:

[{'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}]

1 个答案:

答案 0 :(得分:0)

问题是API返回包含单个元素的列表,因此您可以使用strtLoc = strtLoc[0]访问该列表。然后,您可以访问位置键下的lat和lng属性。

strtLoc = strtLoc[0]
location = strtLoc['geometry']['location']
lat = location['lat']
lng = location['lng']

如果您希望将其作为单个字符串,则可以使用str.join()

以逗号连接它们
location = ','.join([str(lat), str(lng)])