Magick Media Tech Blog

Using Google Maps API to Calculate Distance

A recent project requirement involved calculating the distance between two postal code addresses.  At the time of this writing calls to the Google APIs are limited to 15,000 calls per day.  This seems like an adequate amount today but will it stand up to tomorrows demands as this website expands in popularity?  The solution was to create a lookup table in MySQL storing the postal or zip code and corresponding latitude and longitude data.  When the distance calculation routine is called, it first attempts to lookup the latitude and longitude values from the database using the zip/postal code as the query key.  If none is found, a call is made to the Google API and the resulting latitude and longitude values are inserted into the table.  Over time as the table grows, less and less calls to the Google API are necessary reducing the dependancy.

To get the latitude and longitude data from Google is relatively simple.  The following PHP function does the trick:

function getGoogleMapsLnt($postalzip) {
   $url = “http://maps.googleapis.com/maps/api/geocode/json?address=”.urlencode($postalzip).”&sensor=false”;
   $resultstring = file_get_contents($url);
   $result = json_decode($resultstring, true);
   return $result[‘results’][0][‘geometry’][‘location’];
}

This obviously must be done twice.  Once for the starting coordinate and a second time for the ending coordinate.  

The function is then called like this:

$lntvalues = getGoogleMapsLnt(“90210”);
$latitude = $lntvalues[‘lat’];
$longitude = $lntvalues[‘lng’];

Calculating the distance is accomplished with another helper function:

function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
   $earth_radius = 6371;

   $dLat = deg2rad($latitude2 – $latitude1);
   $dLon = deg2rad($longitude2 – $longitude1);

   $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
   $c = 2 * asin(sqrt($a));
   $d = $earth_radius * $c;

   return $d;
}

Hope this helps someone out there…

Drake Moore

Leave a Reply

Your email address will not be published. Required fields are marked *