Search code examples
pythongoogle-mapszipcodepostal-code

Calculate (road travel) distance between postcodes/zipcodes python


I have a csv file with start and end postcodes (UK equivalent of US zipcodes) and would like to compute simple distance, road travel distance and travel time between the two. I guess the way to go would be to use Google maps in one way or another. I first tried using some spreadhsheet and the following url http://maps.google.com/maps?saddr="&B2&"&daddr="&A2&" but

  1. I do not know how to retrieve the resulting distance from google maps
  2. I would like to know some more pythonic way to work this out

Solution

  • 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