How to calculate distance between two zip codes in python

The main issue with finding a distance between 2 postcodes is that they aren't designed for it.

For the purposes of directing mail, the United Kingdom is divided by Royal Mail into postcode areas. -Wikipedia

A postcode by itself provides no useful information, so you are correct you need help from an external source. The Google maps service at http://maps.google.com is of no use, as it's not designed for you to retrieve information like this.


Option 1 - Google Maps API

The Google Maps API is feature packed and will provide you with a lot of options. The link above is to the Distance Matrix API, which will help with working out distances between 2 points. The results from this will be based on travel (so driving distance), this may or may not be what you want.

Example

Python 3

import urllib.request
import json

res = urllib.request.urlopen("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=SE1%208XX&destinations=B2%205NY").read()
data = json.loads(res.decode())
print(data["rows"][0]["elements"][0]["distance"])
# {'text': '127 mi', 'value': 204914}

Note: Google Maps API is subject to usage limits.

Option 2 - Do it yourself with postcodes.io

postcodes.io has a nice API backed by a public data set. Example lookup. Results are in JSON which can be mapped to a Python dictionary using the json module. The downside here is it provides no way to check distance, so you will have to do it yourself using the Longitude and Latitude returned.

Example

Python 3

import urllib.request
import json

res = urllib.request.urlopen("http://api.postcodes.io/postcodes/SE18XX").read()
data = json.loads(res)
print(data["result"]["longitude"], data["result"]["latitude"])
# -0.116825494204512 51.5057668390097

Calculating distance

I don't want to get too much into this because it's a big topic and varies greatly depending on what you're trying to achieve, but a good starting point would be the Haversine Formula, which takes into account the curvature of the Earth. However, it assumes the Earth is a perfect sphere (which it's not).

The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles.

Here is an example of it implemented in Python: https://stackoverflow.com/a/4913653/7220776

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

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

How do you find the distance between two places in Python?

The math. dist() method returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point. Note: The two points (p and q) must be of the same dimensions.