Apr 04 2008
Apr 04 2008
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.
1 #!/usr/bin/env python 2 # Distance Module 3 # by Pravin Paratey (pravinp at gmail dot com) 4 # Code is licenced under Creative Commons Attribution-Noncommercial-Share Alike 2.5 India 5 # http://creativecommons.org/licenses/by-nc-sa/2.5/in/ 6 7 import urllib2, cgi, re 8 from math import sqrt 9 10 class Distance: 11 """ 12 Using yahoo maps api (http://developer.yahoo.com/maps/rest/V1/geocode.html), 13 this class is responsible for returning the euclidean distance between 14 two places 15 """ 16 def getDistance(self, start, end): 17 """ Gets the euclidean distance between start and end """ 18 (start_x, start_y) = self.getCoords(start) 19 (end_x, end_y) = self.getCoords(end) 20 # 1 degree = 111.12 kms or 69.047 miles 21 return sqrt((start_x - end_x) ** 2 + (start_y - end_y) ** 2) * 111.12 22 23 24 def getCoords(self, location): 25 """ Gets the co-ordinates for the given location """ 26 url = 'http://local.yahooapis.com/MapsService/V1/geocode?appid=' + 27 API_KEY + '&street=' + urllib2.quote(location) 28 response = urllib2.urlopen(url) 29 (x, y) = self._parseXML(response.read()) 30 return float(x), float(y) 31 32 33 def _parseXML(self, xml): 34 """ Parses XML and returns latitude and longitude """ 35 m = re.findall('<latitude>(\d+.\d+)</latitude><longitude>(\d+.\d+)</longitude>', xml) 36 # In case of multiple matches, return 1st match 37 return m[0] 38 39 if __name__ == '__main__': 40 d = Distance() 41 print 'Distance in kms: ' 42 print d.getDistance("Hiranandani, Powai, Mumbai", "Dadar Station, Mumbai")