Calculate driving distance between two points using Google Maps API in PHP

The Distance Matrix API (Google Map API) is a service that provides travel distance and time for a matrix of origins and destinations, based on the recommended route between start and end points.

To get a Driving distance between to two points first, we should have latitude and longitude of each point.

In our example point, One has $lat1 and $long1 variables and same for point two has $lat2 and $long2 variables

function GetDrivingDistance($lat1, $lat2, $long1, $long2)
    $url = "".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=en&key="{{ YOUR_GOOGLE_API_KE }}";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $result = curl_exec($ch);
    $response = json_decode($result, true);
    $distance = $response['rows'][0]['elements'][0]['distance']['text'];
    $time = $response['rows'][0]['elements'][0]['duration']['text'];

    return array('distance' => $distance, 'time' => $time);


  1. Hello,

    How to use google map api Place Autocomplete service and restrict cities to a specific country.
    Do you have an example ?

    Thank’s in advance
    Best regards

Leave a Reply

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