Skip to content

Instantly share code, notes, and snippets.

@yxkelan
Last active August 29, 2015 14:19
Show Gist options
  • Save yxkelan/bc6bd83937f54a7e6102 to your computer and use it in GitHub Desktop.
Save yxkelan/bc6bd83937f54a7e6102 to your computer and use it in GitHub Desktop.
Using google's geocode api to get latitude and longitude for given locations.
# Read location name from locations.txt
# Query location one by onE
import csv
from geopy.geocoders import GoogleV3
def add_geo_info(geolocator, location, writer):
try:
geoinfo = geolocator.geocode(query=location, components={'locality': 'SF'})
if geoinfo:
writer.writerow((location, geoinfo.latitude, geoinfo.longitude))
else:
print 'Cannot get geocode for - ' + location
except:
print 'Error happens for - ' + location
def main():
f = open('locations.txt', 'r');
fcsv = open('geoinfo.csv', 'wt');
try:
writer = csv.writer(fcsv)
writer.writerow(('Locations', 'lat', 'lon'));
geolocator = GoogleV3(api_key="HERE_PUTS_API_KEY")
for line in f.readlines():
location = line.strip('\n')
add_geo_info(geolocator, location, writer)
finally:
f.close()
fcsv.close()
if __name__ == '__main__':
main()
# open CSV file, one is orginal, and another is lookup file.
#
# ['Title', 'Release Year', 'Locations', 'Fun Facts', 'Production Company', 'Distributor', 'Director', 'Writer', 'Actor 1', 'Actor 2', 'Actor 3']
#
import csv
def main():
filename = 'Film_Locations_in_San_Francisco.csv'
f = open(filename, 'rt')
flocations = open('locations.txt', 'w')
try:
reader = csv.reader(f)
header = True
count = 0
locationmap = {}
for row in reader:
if header:
header = False
continue
else:
if row[2] and (not row[2] in locationmap):
count += 1
locationmap[row[2]] = True
flocations.write(row[2] + '\n')
finally:
print 'The number of unique locations: ' + str(count)
f.close()
flocations.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment