PHP code to calculate distance between any two locations on google map

| January 31, 2017

Following code snippet will help you to calculate the distance between any two locations on google map.

this script is developed using Google map API.

the result will return the distance in Miles unit measurement by default. But you can change the distance to kilometers also.

by following line i have converted meter to miles.

$distance = ($distance * 0.000621371); // from meters to miles

for kilometer unit we can change the line to following

$distance = ($distance * 0.001); // from meters to miles

Requirements

1) Google map distance matrix api key. (https://developers.google.com/maps/documentation/distance-matrix/intro)

2) PHP 5.4+

< ?php

/** Get Distance **/
$addressFrom = 'Delhi Cantt, New Delhi, Delhi';  // Location 1 
$addressTo = 'Chennai, Tamil Nadu'; // Location 2 

$distance = getDistance($addressFrom,$addressTo);
echo 'Distance:' . $distance . ' Miles';

function getDistance ($addressFrom, $addressTo) {
    $from = urlencode($addressFrom);
    $to = urlencode($addressTo);
    
    $api_key = 'googlemap-distance-matrix-api-key'; // Googlemap Distance Matrix API Key (Replace it with acutal API key)
    $units = 'metric'; // metric - returns distances in kilometers and meter, imperial - returns distances in miles and feet. (imperial/metrc)
    
    //Google Map API Reference: https://developers.google.com/maps/documentation/distance-matrix/intro 
    $rest_url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false&units=$units&key=$api_key";
    
    /** curl call **/
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $rest_url, // Gmap service call url
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => "GET",
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    if ($err) {
        echo "cURL Error #:" . $err;
    }
    else {
        $result = $response;
    }

    $data = json_decode($result); // curl result
    
    $distance = 0;    

    foreach ($data->rows[0]->elements as $road) {
        if ($road->status == "OK") {
            $distance = $road->distance->value;
            $distance = ($distance * 0.000621371); // from meteres to miles
            $distance = (float) number_format($distance, 2, '.', ''); // for 2 decimal places 0.00 and no comma for thousand seperator
        }
        else {
            $distance = '';
        }
    }
    return ($distance);
}