rss
logo Home Articles Themes Win32 Archives About
Email: pravinp[at]gmail[dot]com Yahoo: pravinparatey Orkut Profile Facebook Profile Google Talk: pravinp[at]gmail[dot]com MSN: pravinp[at]gmail[dot]com

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

2 Responses (rss) (trackback)

prixie
#1

prixie

April 26th, 2008 at 2:42 pm

uh oh- programming ;p

Vartika
#2

Vartika

May 14th, 2008 at 11:27 am

Hey! Long time, no new postings!?

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Blogroll

Gallery

I'm really bad at flower names Farmer in the rain Elephants bathing Wild Boar - Mudumalai, karnataka Titan Pink me-tall me-hadbad VK Korean Phone I can cook 09.Pune Yellow Lantana hand pump Deer chewing on leaves Haemanthus Multiflorus
This page and its contents are copyright © 2008, Pravin Paratey.