带和不带钥匙的行驶距离谷歌 API



Google似乎表明我需要使用SSL并提供用于距离计算的密钥,因此我正在尝试重新设计我的函数以适应,但结果只能得到0。使用距离矩阵显示的 URL 在浏览器中运行时确实给出了正确的值,但我不确定如何在 PHP 中获取结果。看起来$dataset是空的,所以卷曲调用中一定有问题。有什么想法可以得到距离,有没有办法得到最近的距离而不是最快的距离?

function compareDistance($inLatitude,$inLongitude,$outLatitude,$outLongitude,$units) {
// If one of my own addresses is entered, return 0
if ($inLatitude != $outLatitude && $inLongitude != $outLongitude) :
$googlekey = "ABCDEFG123456";
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$inLatitude,$outLatitude&destinations=$outLatitude,$outLongitude&key=$googlekey";
// Retrieve the URL contents
$c = curl_init();
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_URL, $url);
$jsonResponse = curl_exec($c);
curl_close($c);
$dataset = json_decode($jsonResponse);
if (!$dataset)
return 0;
if (!isset($dataset->routes[0]->legs[0]->distance->value))
return 0;
// Google API returns meters: multiply by .00062 to get miles
$miles = ($dataset->routes[0]->legs[0]->distance->value * .00062);
// Convert units
if ($units == "K") :
return $miles * 1.609344;
elseif ($units == "N") :
return $miles * 0.8684;
else :
return $miles;
endif;
else:
return 0;
endif;
}

$jsonResponse正在输出:

{ "destination_addresses" : [ "44.405159,-121.2556414" ], "origin_addresses" : [ "38.257061,44.405159" ], "rows" : [ { "elements" : [ { "status" : "ZERO_RESULTS" } ] } ], "status" : "OK" } 

这现在可以工作,并且可以以英里、海里、公里或米的形式给出输出。使用 Google API,不需要单位参数,因为原始输出始终以米为单位。我还通过将纬度/经度提交为逗号分隔的对而不是单独提交每个来简化它

function compareDistance($inLocation,$outLocation,$units,$googlekey) {
// If one of my own addresses is entered, return 0
if ($inLocation != $outLocation) :
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$inLocation&destinations=$outLocation&mode=driving&key=$googlekey";
// Retrieve the URL contents
$c = curl_init();
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FRESH_CONNECT, true);
curl_setopt($c, CURLOPT_URL, $url);
$jsonResponse = curl_exec($c);
curl_close($c);
$dataset = json_decode($jsonResponse);
if (!$dataset)
return 0;
if (!isset($dataset->rows[0]->elements[0]->distance->value))
return 0;
$meters = $dataset->rows[0]->elements[0]->distance->value;
// Convert default meters to other units
if ($units == "M") :
return ($meters / 1609.344); // Miles
elseif ($units == "N") :
return ($meters / 1852); // Nautical miles
elseif ($units == "K") :
return ($meters * 0.001); // Kilometers
else :
return $meters;
endif;
else:
return 0;
endif;
}

最新更新