使用Python提取纬度和经度

3

我想从实际地址中提取纬度和经度。

我看过一些视频,帮助我编写以下脚本,但是出现了错误。

Lat=Geocode_Result[0]["geometry"]["Location"]["Lat"]
KeyError: 'Location'

  import pandas as pd
  import googlemaps code
  df=pd.DataFrame({'Address':['9 RUE DU FOSSE, L-7772, luxembourg', '37 RUE DE LA GARE,
  L-7535, luxembourg']})      # Creating a dataframe with 2 addresses (its just an example)              
  Gmaps_key=googlemaps.Client("xxxxxxxxx")

  df['Latitude'] = None
  df['Longitude'] = None

  for i in range(len(df)):
   Geocode_Result=Gmaps_key.geocode(df.loc[i,'Address'])  # sending a request for each of the addresses

  Lat=Geocode_Result[0]["geometry"]["Location"]["Lat"]  # Extracting the Latitude information
  Long=Geocode_Result[0]["geometry"]["Location"]["Long"] # Extracting the Longitude information
  df.loc[i,'Latitude'] = Lat   # Pass the information into the DataFrame
  df.loc[i,'Longitude'] = Long

 print(df)   
2个回答

2

您需要先安装geopy(pip install geopy)并导入Nominatim。我对您的代码进行了一些修改以获得输出结果。

import pandas as pd
from geopy.geocoders import Nominatim

df=pd.DataFrame({'Address':['9 RUE DU FOSSE, L-7772, luxembourg', '37 RUE DE LA GARE,L-7535, luxembourg']})         
df['Latitude'] = None
df['Longitude'] = None
locator = Nominatim(user_agent="myGeocoder")
for i in range(len(df)):
    location = locator.geocode(df.loc[i,'Address'])
    df.loc[i,'Latitude'] = location.latitude   
    df.loc[i,'Longitude'] = location.longitude
print(df) 

输出:

                                 Address Latitude Longitude
0    9 RUE DU FOSSE, L-7772, luxembourg   49.789   6.06569
1  37 RUE DE LA GARE,L-7535, luxembourg  49.7684   5.52118

1
亲爱的@Priya,感谢您的贡献。我对附加的代码有一个问题。这个附加的代码是否也使用了Google API?我在想是否可以使用免费服务来转换地址(而不使用Google服务)。 - Wisam hasan
1
代码不使用Google API,仅免费。它类似于安装Pandas(pip install pandas)。您只需要安装geopy即可。 - Priya

0
错误提示说在Geocode_Result[0]["geometry"]中没有键为Location的值。尝试打印该对象?
print(Geocode_Result[0]["geometry"])

文档中对你收到的响应有什么说明?

另外,尝试使用location而不是Location


我无法回答第二个问题,因为我不知道任何地理编码库。尝试搜索一下有哪些可用的Python地理编码库。 - luis.parravicini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接