0

I want to automate a task in Python with the Google API Search Place. Right now, my code with Google Maps API is returning places 'hospital' for one set of geographic coordinates.

But, I have a CSV file which contains many geographic coordinates.

1: Hanoi 10.762622, 106.660172
2: Ho Chi Minh 12.762622, 108.660175
3: Ho Chi Minh 11.8542, 108.660175 
4: ...
5: ...

As you can see in my code, this is not efficient because I need to change the geographic coordinates manually.

For each row (geographic coordinates) in my CSV file, I want my code to read the geographic coordinates 1: Hanoi and give me results 'hospitals' for this geographic coordinates. After read row 2: Ho Chi Minh and same for all the other rows.

How I can achieve that or any good examples of making tasks like this more efficient?

import urllib
import urllib.request
import json

googleGeocodeUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='
keyword = "hospital"
geolocation = "&location=-12.135,-77.023&radius=5000"
APIKEY = '&key='+'apikey'

url = googleGeocodeUrl + keyword + geolocation + APIKEY
print(url)

url = googleGeocodeUrl + keyword + geolocation + APIKEY
json_response = urllib.request.urlopen(url)
search = json_response.read().decode('utf-8')
searchjson = json.loads(search)

export = open('hopital.csv','w')
for place in searchjson['results']:
    print(place['name'])
    print(place['geometry']['location'])
export.write(place['name']+','+str(place['geometry']['location']['lng'])\
 +','+str(place['geometry']['location']['lat'])+'\n')
export.close() 
  • I would suggest to use (geo)pandas and geopy to make your life easier. – RutgerH Sep 17 '18 at 6:25
0

If I understand right, you have the CSV file that has an ID, City, Lat, Lng and you want to line by line populate the geolocation variable with the right values. You need to read the CSV into an array and for each item in the array run your code.

import csv

filename = "C:/gistemp/samplefile.csv"
# ID, city, lat, lng
# 1: Hanoi 10.762622, 106.660172


f = open(filename, "rU")
reader = csv.reader(f, delimiter=",")

rownum = 0  
arr = []

for i in reader:
    arr.append (i)
    rownum += 1

f.close()


for i in arr:
    ID = i[0]
    city = i[1]
    lat = i[2]
    lng = i[3]
    # reat of your code inside this loop...



    #geolocation = "&location=" + lat + "," + lng + "&radius=

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.