3

I'm trying to extract the Latitude and Longitude from actual address.

I have seen some videos that help me to write the following script, but i have an error showing

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)   
0

2 Answers 2

2

You need to first install geopy (pip install geopy) and import Nominatim. I have made few modifications to your code to get the output.

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) 

Output:

                                 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
Sign up to request clarification or add additional context in comments.

2 Comments

dear@Priya, thanks for your contribution. I have one question to the attached code. Does the attache code use the Google API as well, I was wondering if I can use free service to convert the address (without using Google service)
The code does not use Google API. It's free only. It is similar to how you install Pandas (pip install pandas) . You just need to install geopy.
0

The error is saying there's no key Location in Geocode_Result[0]["geometry"]. Try printing the object?

print(Geocode_Result[0]["geometry"])

What does the docs say about the response you get?

Also, try using location instead of Location?

1 Comment

Can't help you with question 2 as I don't know any geocoding lib. Try googling which geocoding python libraries are available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.