-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)]) 
相關問題