【问题标题】:Get distance between two location using google api使用google api获取两个位置之间的距离
【发布时间】:2012-12-12 16:03:10
【问题描述】:

我有以下代码:

$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 值意味着函数无法解码它。

这背后的原因是什么?

【问题讨论】:

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


    【解决方案1】:

    返回值包含格式错误的 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

    【讨论】:

      【解决方案2】:

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

      $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";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-30
        • 1970-01-01
        • 1970-01-01
        • 2013-08-21
        • 1970-01-01
        • 2016-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多