Hello, I am an Engineering Manager at Facebook with 13+ years in Ad Technology, Natural Language Processing and Data mining. (Learn More)
by Pravin Paratey

Euclidean Distance Calculator

The following snippet returns the euclidean distance between two places on the globe using the Yahoo Maps API. Replace API_KEY with your Yahoo Maps API key.

#!/usr/bin/env python
# Distance Module
# by Pravin Paratey (pravinp at gmail dot com)
# Code is licenced under Creative Commons Attribution-Noncommercial-Share Alike 2.5 India
# http://creativecommons.org/licenses/by-nc-sa/2.5/in/

import urllib2, cgi, re
from math import sqrt

class Distance:
    """
    Using yahoo maps api (http://developer.yahoo.com/maps/rest/V1/geocode.html),
    this class is responsible for returning the euclidean distance between
    two places
    """
    def getDistance(self, start, end):
        """ Gets the euclidean distance between start and end """
        (start_x, start_y) = self.getCoords(start)
        (end_x, end_y) = self.getCoords(end)
        # 1 degree = 111.12 kms or 69.047 miles
        return sqrt((start_x - end_x) ** 2 + (start_y - end_y) ** 2) * 111.12


    def getCoords(self, location):
        """ Gets the co-ordinates for the given location """
        url = 'http://local.yahooapis.com/MapsService/V1/geocode?appid=' +
                API_KEY + '&street=' + urllib2.quote(location)
        response = urllib2.urlopen(url)
        (x, y) = self._parseXML(response.read())
        return float(x), float(y)


    def _parseXML(self, xml):
        """ Parses XML and returns latitude and longitude """
        m = re.findall('<latitude>(\d+.\d+)</latitude><longitude>(\d+.\d+)</longitude>', xml)
        # In case of multiple matches, return 1st match
        return m[0]

if __name__ == '__main__':
    d = Distance()
    print 'Distance in kms: '
    print d.getDistance("Hiranandani, Powai, Mumbai", "Dadar Station, Mumbai")