Rub*_*len 3 php json distance matrix google-maps-api-3
客户要求我计算从某个地址到固定地址的距离.我使用Google Distance Matrix API制作了一个PHP脚本来计算距离.但是,这并没有给我最短的距离.它似乎只是给了谷歌认为最好的东西.例如,我的脚本在2个地址之间返回11.7公里,而Google地图则提供以下结果:
如你所见,8.7km与11.7km相比差别很大.
我会考虑除Google Distance Matrix API之外的其他选项.
我的剧本:(简而言之)
if ($this->getVar('to', false) && $this->getVar('to', false) != '') {
$to = urlencode(urldecode($this->getVar('to', false)));
$url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=Etterbeeksesteenweg+180+Brussel&destinations='.$to.'&mode=driving&language=nl-BE&sensor=false';
$this->view->response = json_decode(file_get_contents($url));
}
Run Code Online (Sandbox Code Playgroud)
我试图添加&alternatives=true
,但没有成功.
Dr.*_*lle 16
DistanceMatrixService(以及DirectionsService)通常不会返回最短路径,它们将返回最快的路径.
使用DirectionsService而将其他参数alternatives
设置为true:
当您添加alternatives
-parameter时,您还会获得备用路径,当您检查返回的结果时,您将看到它还包含9km路径.但是这条路线的持续时间为17分钟,而建议的(较长的)路线的持续时间为16分钟,这就是为什么较长的路线是建议的路线.
因此,从返回的路径中获取最短路径.
例:
<?php
//request the directions
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=bomerstraat%2018,%20peer&destination=kievitwijk%2028,%20helchteren&alternatives=true&sensor=false'))->routes;
//sort the routes based on the distance
usort($routes,create_function('$a,$b','return intval($a->legs[0]->distance->value) - intval($b->legs[0]->distance->value);'));
//print the shortest distance
echo $routes[0]->legs[0]->distance->text;//returns 9.0 km
?>
Run Code Online (Sandbox Code Playgroud)
注意:您可能会在google-maps和服务上获得不同的结果,因为google-maps会考虑当前的流量情况,但服务不会(除非您拥有营业执照)
归档时间: |
|
查看次数: |
17824 次 |
最近记录: |