如何从python3中的googlegeocodeapi获取lat/long?

2024-05-16 02:57:53 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用下面的代码时,我得到了很多数据,但我只想存储lat,只要一个字符串。在

它看起来像一个字典,我试图像一个字典一样访问它:strtLoc['location'],但刚得到一个索引must be int error。当我尝试索引时,只有一个条目,len(strtLoc)返回1。在javascript中我看到了strtLoc.位置但是我不知道如何在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}]

Tags: 代码namenew字典addresslocationlongtypes
1条回答
网友
1楼 · 发布于 2024-05-16 02:57:53

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

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

如果您希望它作为单个字符串,可以使用str.join()用逗号将它们连接起来

^{pr2}$

相关问题 更多 >