Get driving distance between two points using Google Maps API

后端 未结 5 2174
Happy的楠姐
Happy的楠姐 2020-12-12 18:53

I\'m trying to get driving distance between two points using Google Maps API. Now, I have code which get direct distance:

This function get lat and

5条回答
  •  甜味超标
    2020-12-12 19:20

    OK, I found solution using distance matrix: https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixRequests

    This function get lat & lng from city, adress, province:

    function get_coordinates($city, $street, $province)
    {
        $address = urlencode($city.','.$street.','.$province);
        $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=Poland";
        $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);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_a = json_decode($response);
        $status = $response_a->status;
    
        if ( $status == 'ZERO_RESULTS' )
        {
            return FALSE;
        }
        else
        {
            $return = array('lat' => $response_a->results[0]->geometry->location->lat, 'long' => $long = $response_a->results[0]->geometry->location->lng);
            return $return;
        }
    }
    

    This function calculate driving distance and travel time duration:

    function GetDrivingDistance($lat1, $lat2, $long1, $long2)
    {
        $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL";
        $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);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_a = json_decode($response, true);
        $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
        $time = $response_a['rows'][0]['elements'][0]['duration']['text'];
    
        return array('distance' => $dist, 'time' => $time);
    }
    

    Usage:

    $coordinates1 = get_coordinates('Tychy', 'Jana Pawła II', 'Śląskie');
    $coordinates2 = get_coordinates('Lędziny', 'Lędzińska', 'Śląskie');
    if ( !$coordinates1 || !$coordinates2 )
    {
        echo 'Bad address.';
    }
    else
    {
        $dist = GetDrivingDistance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long']);
        echo 'Distance: '.$dist['distance'].'
    Travel time duration: '.$dist['time'].''; }

    Return:

    Distance: 11,2 km Travel time duration: 15 min

提交回复
热议问题