使用google api获取两个位置之间的距离

时间:2012-12-27 08:38:25

标签: php google-maps google-maps-api-3

我有以下代码:

$output = file_get_contents("http://maps.google.com/maps/nav?q=from:39.519894,-5.105667%20to:51.129079,1.306925");

$distance = json_decode($output);

我从Google API获得了JSON响应,但是当我使用json_decode()解码JSON时,我得到一个NULL值意味着该函数无法对其进行解码。

这背后的原因是什么?

2 个答案:

答案 0 :(得分:3)

这应该对你有用,你可以将地址或纬度/经度传递给$ from& $对

$from = "Więckowskiego 72, Łódź";
$to = "Gazowa 1, Łódź";

$from = urlencode($from);
$to = urlencode($to);

$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);

$time = 0;
$distance = 0;

foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}

echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "Time: ".$time." seconds";
echo "<br/>";
echo "Distance: ".$distance." meters";

答案 1 :(得分:2)

返回的值有错误的UTF-8字符,可能是因为编码错误。您所需要的只是utf8_encode

$json = file_get_contents('http://maps.google.com/maps/nav?q=from:39.519894,-5.105667%20to:51.129079,1.306925');
$data = json_decode(utf8_encode($json),true);
var_dump($data);

See Live Demo