google-maps - 带和不带密钥的行驶距离 Google API
问题描述
谷歌似乎表明我需要使用 SSL 并提供距离计算的密钥,所以我试图重新设计我的函数以适应但只能得到 0 作为结果。使用 distancematrix 显示的 URL 在浏览器中运行时确实给出了正确的值,但我不确定如何在 PHP 中获取结果。看来 $dataset 是空的,所以 curl 调用中一定有问题。获得距离的任何想法,有没有办法获得最近的距离而不是最快的距离?
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;
}
推荐阅读
- python - Pythonic(和最高效)的方式来生成所有点之间的距离,同时保持元数据?
- django - django 2.1.2 后端认证失败
- macos - 没有任何布局约束的视图可能会被裁剪 - 使用 AutoresizingMask
- c - 添加两个大数字作为字符串
- hadoop - 将任何大小和格式的文件发送到 Hadoop 的最快方法是什么?
- python - 图像的多输入 CNN
- javascript - 如何重新运行/重用类构造函数
- c# - 从一个单词搜索和无法访问的代码中返回整个字符串
- javascript - 如何在 Gulp 4 中将函数作为任务运行?
- python-3.x - 获取前 10 个和后 10 个功能