-1

当使用下面的代码我得到了很多的数据,但我只想纬度保存,只要一个字符串。如何从python 3中的google地理编码API获取lat/long?

它看起来像一本字典,我试图访问它像一个:strtLoc['location']只是得到了一个索引必须是int错误。当我试图索引只有一个入口和len(strtLoc)回报1.在javascript中我见过类似的东西strtLoc.location但我无法弄清楚如何只得到lat和长蟒蛇。

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}] 
+0

它开始'['一个逗号,它使一个列表加入他们的行列。它包含一个字典。尽量去坐标。 –

+0

我也尝试过使用索引,但只有strtLoc [0]包含所有上述数据。我也为gmaps.geocode(address = startP):strtLoc.append(item)'中的项目尝试了一个for循环'并且有同样的问题。 – user6912880

回答

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)]) 
相关问题