Created
January 27, 2009 21:35
-
-
Save mamuso/53566 to your computer and use it in GitHub Desktop.
Distance between two addresses using google maps and the Haversine forumla
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'open-uri' | |
require "rexml/document" | |
# | |
# | |
# Distance between two addresses using google maps and the Haversine forumla | |
# (http://en.wikipedia.org/wiki/Haversine_formula) based on the JS implementation | |
# (http://www.movable-type.co.uk/scripts/latlong.html) | |
# | |
# | |
GM_APIKEY = "ABQIAAAAuunGS_VtjHf9ymsKEjhoRBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQiRG09L8LvCecfieIFyIMNkGEZxg" | |
def get_distance(address1, address2) | |
pointA = get_coordinates(address1) | |
pointB = get_coordinates(address2) | |
# Haversine rules :) | |
earth_radius = 6371 # km | |
dLat = ((Float(pointA[0])-Float(pointB[0]))*Math::PI)/180 | |
dLon = ((Float(pointA[1])-Float(pointB[1]))*Math::PI)/180 | |
a = Math.sin(dLat/2) * Math.sin(dLat/2) + | |
Math.cos((Float(pointA[0])*Math::PI)/180) * Math.cos((Float(pointB[0])*Math::PI)/180) * | |
Math.sin(dLon/2) * Math.sin(dLon/2) | |
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) | |
d = earth_radius * c | |
end | |
def get_coordinates(address) | |
doc = REXML::Document.new(open("http://maps.google.com/maps/geo?q=#{address.gsub(" ", "+")}&output=xml&key=#{GM_APIKEY}")) | |
doc.elements.to_a("//coordinates").first.text.split(",") | |
end | |
# using postal code and country code | |
get_distance("03400 ES", "28002 ES") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment