Created
August 23, 2011 17:22
-
-
Save johnlettman-old/1165912 to your computer and use it in GitHub Desktop.
Haversine Implementation in PHP with Coordinate Lookup from named addresses.
This file contains hidden or 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
<?php | |
function getCoordinatesFromAddress($address) | |
{ | |
if(!is_string($address)) return false; | |
$result = false; | |
if($result = file_get_contents('http://maps.google.com/maps?output=js&q=%s' . rawurlencode($address))) | |
{ | |
if(strpos($result, 'errortips') > 1 || strpos($result, 'Did you mean:') !== false) return false; | |
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $result, $match); | |
$coords['lat'] = $match[1]; | |
$coords['long'] = $match[2]; | |
} | |
return $coords; | |
} | |
function haversine($lat1, $long1, $lat2, $long2, $radius) | |
{ | |
$distanceLat = deg2rad($lat2 - $lat1); | |
$distanceLon = deg2rad($long2 - $long1); | |
$a = sin($distanceLat / 2) * sin($distanceLat / 2) + | |
sin($distanceLon / 2) * sin($distanceLon / 2) * cos(deg2rad($lat1)) * cos(deg2rad($lat2)); | |
$c = 2 * atan2(sqrt($a), sqrt(1 - $a)); | |
return $radius * $c; | |
} | |
define('EARTH_R_KM', 6371); | |
$wh = getCoordinatesFromAddress('1600 Pennsylvania Avenue, Washington D.C., DC 20500'); | |
$ms = getCoordinatesFromAddress('Microsoft Corporation One Microsoft Way Redmond, WA 98052-6399'); | |
echo haversine($wh['lat'], $wh['long'], $ms['lat'], $ms['long'], EARTH_R_KM) . ' Kilometers'; |
This file contains hidden or 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
a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2) | |
c = 2.atan2(√a, √(1−a)) | |
d = R.c |
Wow, so many problems with Gist right now. Had to re-edit this so many times.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Weird, Gist is messing up the whitespace.