Get kilometer from two pincode / zipcode in google map


<?php
/**
* GETCOORD
* Uses Google Maps to resolve the coordinates of a postal code
*
* @param   String   $postal   Postal code to lookup
* @return  Array    Returns array with latitude and longitude
* @return  Boolean  False if an error occurred
*/

// —- | REQUIRED GOOGLE MAPS KEY | ——–
// Get yours here: http://www.google.com/apis/maps/signup.html
define(‘KEY’, ‘ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxSPW5CJgpdgO_s4yyMovOaVh_KvvhSfpvagV18eOyDWu7VytS6Bi1CWxw’);

function getCoord($postal)
{
$d = file_get_contents(‘http://maps.google.com/maps/geo?q=&#8217; . $postal . ‘&output=xml&key=’ . KEY);
if (!$d)
return false; // Failed to open connection

$coord = new SimpleXMLElement($d);

if ((string) $coord->Response->Status->code != ‘200’)
return false; // Invalid status code

list($lng, $lat) = explode(‘,’, (string) $coord->Response->Placemark->Point->coordinates);

return array(‘Lat’ => (float) $lat, ‘Lng’ => (float) $lng);
}

/**
* CALCDISTANCE
* Calculates the distance between to postal codes
*
* @param   String   $postal1   Starting postal code
* @param   String   $postal2   Ending postal code
* @return  Float    Returns distance in kilometers
* @return  Boolean  False if an error occurred
*/
function calcDistance($postal1, $postal2)
{
$dst1 = getCoord($postal1);
$dst2 = getCoord($postal2);

if (!$dst1 or !$dst2)
return false; // Invalid postal codes

$kms = rad2deg(acos(sin(deg2rad($dst1[‘Lat’])) * sin(deg2rad($dst2[‘Lat’])) +
cos(deg2rad($dst1[‘Lat’])) * cos(deg2rad($dst2[‘Lat’])) *
cos(deg2rad($dst1[‘Lng’] – $dst2[‘Lng’])))) * 60 * 1.1515 * 1.609344;

return $kms;
}

echo calcDistance(‘1790’, ‘1795’) . ‘ kms’; // prints 37…. kms
?>

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s