04 May, 2010

Find distance between two cities using lattitude and longitude using Google Maps


Distance can be calculated using lattitude and longitude obtained from google maps api, using the following code:
//Get the lattitude and longitude of two cities first -- returns json format data
$address1 = urlencode($addressLine1).",+".urlencode($city1).",+".urlencode($statePrefix1);
$address2 = urlencode($addressLine2).",+".urlencode($city2).",+".urlencode($statePrefix2);

$geoCode1 = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".$address1."&sensor=false");
$geoCode2 = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".$address2."&sensor=false");

//now get lat and long
$output1 = json_decode($geoCode1);
$lat1 = $output1->results[0]->geometry->location->lat;
$lng1 = $output1->results[0]->geometry->location->lng;

$output2 = json_decode($geoCode2);
$lat2 = $output2->results[0]->geometry->location->lat;
$lng2 = $output2->results[0]->geometry->location->lng;

//now get the distance
calculate_distance($lat1, $lng1, $lat2, $lng2, "K");

//function calculate_distance
function calculate_distance($lat1, $long1, $lat2, $long2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
}
else if ($unit == "N") {
return ($miles * 0.8684);
}
else {
return $miles;
}
}