April 3rd, 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #!/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") |

I'm your average, everyday chap who enjoys chocolate, free food and the occasional, dirty picture of Terry Farell. [
Comments (rss) (trackback)
on April 26th, 2008 @ 2:42 pm
uh oh- programming ;p
on May 14th, 2008 @ 11:27 am
Hey! Long time, no new postings!?
Add a Comment: