Skip to content

Instantly share code, notes, and snippets.

@sudevschiz
Created January 29, 2016 07:04
Show Gist options
  • Save sudevschiz/852b1ca3aa0d3e94d1e0 to your computer and use it in GitHub Desktop.
Save sudevschiz/852b1ca3aa0d3e94d1e0 to your computer and use it in GitHub Desktop.
Python script to find distance between two zipcodes. May use Google or Bing APIs
import urllib2
import csv
import json
import time
#Output file
out_file = open('distance_output.csv','a')
i = 0
na_count = 0
with open('zip_to_geocode.csv', 'rt') as in_file:
try:
reader = csv.reader(in_file)
writer = csv.writer(out_file, delimiter=',')
#TODO
api_key_bing = [Enter your bing api key here]
api_key_google = [Enter your google api key here]
for row in reader:
i = i+1
#print(" ".join(row))
line = " ".join(row).split()
order_id = line[0]
zip1 = line[1].zfill(5)
zip2 = line[2].zfill(5)
#Use the suitable service. Comment the other
#def_google_url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="+zip1+"&destinations="+zip2+"&mode=car&sensor=false&api_key="+api_key_google
def_bing_url = "http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0="+ zip1 +"&wp.1="+zip2 + "&avoid=minimizeTolls&key=" + api_key_bing
#The row from which geocoding has to start
start_row = 1
if(i<start_row):
continue
else:
print order_id
#Set the sleep time here to reduce the frequency of API call
if(i%2 == 0):
time.sleep(0.5)
#Set a limit on NA values
if(na_count > 4):
print("Limits exceeded")
break
try:
response = urllib2.urlopen(def_bing_url)
data = json.load(response)
#Enable the following lines if using Google webserive instead of Bing
#dist = data['rows'][0]['elements'][0]['distance']['value']
#dist = dist/1000.0
#na_count = 0
dist = data['resourceSets'][0]['resources'][0]['travelDistance']
na_count = 0
except:
dist = "NA"
na_count = na_count +1
#Save into a file
print str(dist)+","+str(i)+"\n"
writer.writerow([order_id,zip1,zip2,str(dist)])
finally:
in_file.close()
out_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment