SethCalkins
12/23/2014 - 3:40 AM

distances.py

import requests
import math
from BeautifulSoup import BeautifulSoup

def distance_on_unit_sphere(lat1, long1, lat2, long2):
    "src: http://www.johndcook.com/python_longitude_latitude.html"
    degrees_to_radians = math.pi/180.0

    phi1 = (90.0 - lat1)*degrees_to_radians
    phi2 = (90.0 - lat2)*degrees_to_radians
    theta1 = long1*degrees_to_radians
    theta2 = long2*degrees_to_radians
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + 
           math.cos(phi1)*math.cos(phi2))
    arc = math.acos( cos )
    return arc * 3960 # To get the distance in kilometers, multiply by 6373 instead

def main():
    r = requests.get('http://www.freemaptools.com/ajax/getaandb.php?a=Sydney_Australia&b=Melbourne_Australia&c=1317')
    xml = BeautifulSoup(r.text)

    lat1 = float(xml.markers.findAll('marker')[0]['lat']);
    lng1 = float(xml.markers.findAll('marker')[0]['lng']);
    lat2 = float(xml.markers.findAll('marker')[1]['lat']);
    lng2 = float(xml.markers.findAll('marker')[1]['lng']);
    
    print distance_on_unit_sphere(lat1, lng1, lat2, lng2)

if __name__ == '__main__':
    main()