Google Maps API - Distance Calculator - PHP Example

This code gets the distance, in miles, between two US Zip codes (04429 and 02135). You can substitute other origins and destinations.


<?php
function curl_request($sURL,$sQueryString=null)
{
        $cURL=curl_init();
        curl_setopt($cURL,CURLOPT_URL,$sURL.'?'.$sQueryString);
        curl_setopt($cURL,CURLOPT_RETURNTRANSFER, TRUE);
        $cResponse=trim(curl_exec($cURL));
        curl_close($cURL);
        return $cResponse;
}

$sResponse=curl_request('http://maps.googleapis.com/maps/api/distancematrix/json',
    'origins=04429&destinations=02135&mode=driving&units=imperial&sensor=false');
$oJSON=json_decode($sResponse);
if ($oJSON->status=='OK')
        $fDistanceInMiles=(float)preg_replace('/[^\d\.]/','',$oJSON->rows[0]->elements[0]->distance->text);
else
        $fDistanceInMiles=0;

echo 'Distance in Miles: '.$fDistanceInMiles.PHP_EOL;

Notes

  • The preg_replace code discards any text, other than the numeric representation of the distance.
  • This was run under PHP 5.2.17, the json_decode function was introduced in version 5.2.0.
  • Be sure to include the sensor input, otherwise, you will get a “REQUEST DENIED”
  • Also be sure to validate and sanitize any inputs as appropriate.

Refer to the link above for additional information.