Google 如果我使用起点和终点变量,距离矩阵 API 不会 return 值

Google Distance Matrix API does not return value if I am using variables of Origin and Destination

我现在正在做一个项目,需要计算两点之间的距离(经纬度或特定地点名称)。

现在,由于我的起点和终点来自我的数据库,我需要使用一个变量来存储起点和终点并最终计算出来。

我的代码是这样的:

<?php
//request the directions
$origin="maramag";
$desti="malaybalay";
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$desti&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;
echo $routes[0]->legs[0]->duration->text;
?>

但是当我在不使用变量的情况下尝试 运行 URL 时,例如:

    $routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=maramag&destination=malaybalay&alternatives=true&sensor=false'))->routes;

它给了我“49.0 公里 45 分钟”的结果,这是我想要显示的结果。

谁能帮我格式化我的变量?我认为这是 URL 中包含的我的变量的格式或语法有问题。

我浏览了 Google 和这个网站,但我从未找到解决问题的方法。

非常感谢!

使用字符串连接运算符创建您的 URL:

$origin="maramag";
$desti="malaybalay"; 
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin='.$origin.'&destination='.$desti.'&alternatives=true&sensor=false'))-  >routes;

如果字符串中包含空格或其他在 URL 中不合法的字符,则 URL 首先对其进行编码。

上面@geocodezip的回答是正确的,但是如果Origin和Destination包含空格会报错。所以我们必须把空格换成“+”来避免。此问题的完整答案如下:

$origin="Dologon, Maramag, Bukidnon";
$desti="Malaybalay City, Bukidnon";

//replace the spaces with "+"
$address1 = str_replace(' ', '+', $origin);
$address2 = str_replace(' ', '+', $desti);

//use concatenation as answered by @geocodezip
$routes=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin='.$address1.'&destination='.$address2.'&alternatives=true&sensor=false'))->routes;

所以我们必须让 origin='.$origin.' 而不是让我们的 origin=$origin 和我们的目的地=#desti。对于目的地,我们必须将其设为 destination='.$desti.'

编码愉快!非常感谢您的帮助!

使用您的代码,我能够通过使用 urlencode 并确保我使用双引号而不是单引号来获得包含空格的地址的正确响应。

这是我所做的一切:

$location = urlencode($location); // May contain spaces
$routes = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/directions/json?origin=$userLat,$userLong&destination=$location&alternatives=true&sensor=false"))->routes;

您的其余代码运行完美,returns 正确的距离和旅行时间。我不需要使用 PHP 的字符串连接语法(即:"Text ". $var ." more text

如果有人好奇,我使用

的答案通过 javascript/PHP 获得了用户的经纬度