Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use gmaps to parse and calculate distance between two points.
#! /usr/bin/env python
""" Use gmaps to parse and calculate distance between two points.
"""
__author__ = 'Micah Elliott http://MicahElliott.com'
__version__ = '0.1'
### -------------------------------------------------------------------
import os, sys
from urllib import urlopen, quote_plus
from xml.dom.minidom import parseString
from simplejson import loads
from math import sqrt
usage = 'geodist "addr1" "addr2"'
units = 'miles'
provider = 'google'
if len(sys.argv) != 3:
print>>sys.stderr, usage
sys.exit(1)
addr1, addr2 = sys.argv[1:3]
##addr1 = 'fort knox'
##addr2 = 'white house'
print "Using %s to calculate distance between: \n %s\n %s\n" % (provider, addr1, addr2)
uri = 'http://maps.google.com/maps/geo?q=%s&output=json'
#uri = 'http://maps.google.com/maps/geo?q=%s&output=json&sensor=true_or_false&key=your_api_key'
lookup1 = uri % addr1
lookup2 = uri % addr2
##print lookup1
def get_ll(lookup):
json = loads( urlopen(lookup).read() )
lat_lon = json['Placemark'][0]['ExtendedData']['LatLonBox']
return lat_lon['east'], lat_lon['north']
lat1, lon1 = get_ll(lookup1)
lat2, lon2 = get_ll(lookup2)
lat_diff = 69.1 * (lat2-lat1)
lon_diff = 53.0 * (lon2-lon1)
dist = sqrt( lat_diff**2 + lon_diff**2 )
print 'Distance: %s %s' % (dist, units)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment