Reputation: 33
I have the latitude and longitude of places in a dataframe. I am looking to get the zip code using Google Maps API. Now I am trying to write a loop to do this and it won't work. The problem is the gmaps variable latlng
How do I get two floats that are my variables into one variable that is latlng
?
I have successfully done this went I "hardcode" in the coordinates.
for index, row in bike_df.iterrows():
lat = row["Starting Station Latitude"]
long = row["Starting Station Longitude"]
target_url = ('https://maps.googleapis.com/maps/api/geocode/json?'
'latlng=34.052898,-118.241562&key={0}').format(gkey)
response = requests.get(target_url).json()
try:
print(response['results'][0]['address_components'][7]['long_name'])
except:
print(f"Could not {index} find zip")
for index, row in bike_df.iterrows():
lat = row["Starting Station Latitude"]
long = row["Starting Station Longitude"]
target_url = ('https://maps.googleapis.com/maps/api/geocode/json?'
'latlng=lat,long&key={0}').format(gkey)
response = requests.get(target_url).json()
try:
print(response['results'][0]['address_components'][7] .
['long_name'])
except:
print(f"Could not {index} find zip")
It just runs and runs without any output.
Upvotes: -2
Views: 847
Reputation: 53
Maybe try this?
import pandas as pd
df = pd.DataFrame({'lat':[34.052898,34.052898,34.052898],
'long':[-118.241562,-118.241562,-118.241562]})
df
for index, row in df.iterrows():
latlng = lat + long
print(latlng)
[34.052898, -118.241562] [34.052898, -118.241562] [34.052898, -118.241562]
lat = row["Starting Station Latitude"]
long = row["Starting Station Longitude"]
target_url = ('https://maps.googleapis.com/maps/api/geocode/json?'
'latlng=lat,long&key={0}').format(gkey)
response = requests.get(target_url).json()
try:
print(response['results'][0]['address_components'][7] .
['long_name'])
except:
print(f"Could not {index} find zip")
Upvotes: 0
Reputation: 318
You should use, like you did with gkey, concatate your variable. You can do it in several way.
For example:
target_url = ('https://maps.googleapis.com/maps/api/geocode/json?'
'latlng='+str(lat)+','+str(long)+'&key={0}').format(gkey)
or somehting like
target_url = ('https://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&key={2}').format(lat, long, gkey)
Upvotes: 0
Reputation: 385
Your lat
and long
variables aren't being inserted in the target_url
string. You'll need to do something like:
target_url = ('https://maps.googleapis.com/maps/api/geocode/json?'
'latlng={lat},{long}&key={gkey}').format(lat=lat,long=long,gkey=gkey)
Upvotes: 0