簡體   English   中英

使用Google Maps API獲取兩點之間的行駛距離

[英]Get driving distance between two points using Google Maps API

我正在嘗試使用Google Maps API獲得兩點之間的行駛距離。 現在,我有直接獲得距離的代碼:

此函數獲取經緯度:

function get_coordinates($city, $street, $province)
{
    $address = urlencode($city.','.$street.','.$province);
    $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=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);
    $return = array('lat' => $response_a->results[0]->geometry->location->lat, 'long' => $long = $response_a->results[0]->geometry->location->lng);

    return $return;
}

此函數根據緯度和經度計算兩點之間的距離:

function getDistanceBetweenPoints($lat1, $lon1, $lat2, $lon2) {
    $theta = $lon1 - $lon2;
    $miles = (sin(deg2rad($lat1)) * sin(deg2rad($lat2))) + (cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $kilometers = $miles * 1.609344;
    return $kilometers;
}

此功能以公里為單位打印距離:

function get_distance($lat1, $lat2, $long1, $long2)
{
    /* These are two points in New York City */
    $point1 = array('lat' => $lat1, 'long' => $long1);
    $point2 = array('lat' => $lat2, 'long' => $long2);

    $distance = getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
    return $distance;
}

用法:

$coordinates1 = get_coordinates('Katowice', 'Korfantego', 'Katowicki');
$coordinates2 = get_coordinates('Tychy', 'Jana Pawła II', 'Tyski');

echo 'Distance: <b>'.round(get_distance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long']), 1).'</b> km';

但是這段代碼獲得直接的距離。 我需要行車距離。 如何使用Google Maps API獲取行駛距離?

謝謝你的幫助!

好的,我找到了使用距離矩陣的解決方案: https : //developers.google.com/maps/documentation/distancematrix/#DistanceMatrixRequests

此功能可從城市,地址,省獲得經緯度:

function get_coordinates($city, $street, $province)
{
    $address = urlencode($city.','.$street.','.$province);
    $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=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;
    }
}

該函數計算行駛距離和行駛時間:

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);
}

用法:

$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: <b>'.$dist['distance'].'</b><br>Travel time duration: <b>'.$dist['time'].'</b>';
}

返回:

距離:11,2 km行車時間:15分鍾

您可以使用Google Distance Matrix API來做到這一點:

// $details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=driving&sensor=false";

    //you can also pass latitude/longitude values in origins


   $details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=41.43206,-81.38992&destinations=San+Francisco&mode=driving&sensor=false";


    $json = file_get_contents($details);

    $details = json_decode($json, TRUE);

    echo "<pre>"; print_r($details); echo "</pre>";

這是Google Distance Matrix API的鏈接:-https: //developers.google.com/maps/documentation/distancematrix/?csw=1

這就是我得到的方法。 在其中,您可以輸入到會話或數據庫的任何手動距離。

$origin      = urlencode($_SESSION['source1']);
$destination = urlencode($_SESSION['dest1']);

$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destination&key=Your api key";

$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);
?>

現在最困難的部分是如何顯示距離。 通過研究,我得到了這個答案:

<div>
     <?php echo $response_a['rows'][0]['elements'][0]['distance']['text']; ?>
</div>

您可以在任何地方打印此結果。 它為我工作。

距離矩陣API將完成工作,然后無需使用地址再按距離來計算坐標!!

這是API
https://maps.googleapis.com/maps/api/distancematrix/json?origins=orginaddress&destinations=destinationaddress&key=YOUR_API_KEY

PHP代碼:

$ch = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=orginaddress&destinations=destinationaddress&key=YOUR_API_KEY";
$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);
//print_( $response_a );

您可以嘗試使用Google Distance Matrix API。 這是下面的示例HTML,PHP代碼。 在這里,您必須使用應用程序密鑰更改“ YOUR_API_KEY”。

<!DOCTYPE html>
<html>
    <body>
        <form action="" method="post">
            <label>Origin:</label> <input type="text" name="o" placeholder="Enter Origin location" required> <br><br>
            <label>Destination:</label> <input type="text" name="d" placeholder="Enter Destination location" required> <br><br>
            <input type="submit" value="Calculate distance & time" name="submit"> <br><br>
        </form>
        <?php
            if(isset($_POST['submit'])){
            $origin = $_POST['o']; $destination = $_POST['d'];
            $api = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$origin."&destinations=".$destination."&key=YOUR_API_KEY");
            $data = json_decode($api);
        ?>
            <label><b>Distance: </b></label> <span><?php echo ((int)$data->rows[0]->elements[0]->distance->value / 1000).' Km'; ?></span> <br><br>
            <label><b>Travel Time: </b></label> <span><?php echo $data->rows[0]->elements[0]->duration->text; ?></span> 

        <?php } ?>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM