【问题标题】:Get url from google.maps json and save the data in a variable从 google.maps json 获取 url 并将数据保存在变量中
【发布时间】:2017-09-15 18:56:06
【问题描述】:

早上好,我需要从 JSON 中获取 google.maps 距离和时间生成的数据,文档中是这个地址:

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=MI_API_KEY

用我的 api 设置它并传递我得到的两个随机方向并显示距离和时间:

<script>
    var respuesta = '{"destination_addresses":["Av. Sagrada Familia 627, 
Cordoba"],"origin_addresses":["9 de Julio 1800, Cordoba"],"rows":[{"elements":[{"distance":{"text":"2,2 
mi","value":3523},"duration":{"text":"9 
min","value":540},"status":"OK"}]}],"status":"OK"}'


  var distancia = JSON.parse(respuesta).rows[0].elements[0].distance.text
 var tiempo = JSON.parse(respuesta).rows[0].elements[0].duration.text

   window.onload = function what(){
    document.getElementById("span_distancia").innerHTML = distancia;
    document.getElementById("span_tiempo").innerHTML = tiempo;
  }
</script>

DISTANCE: <span id="span_distancia"></span><br>
TIME: <span id="span_tiempo"></span><br>

到目前为止一切顺利,现在开始和结束地址不是静态的,在这个例子中我之前放的总是相同的数据,我需要这些数据是动态的,因为到 google.maps 步骤开始的地址并作为变量结束:

https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=VARIABLE_PHP_START&destinations=VARIABLE_PHP_END&key=MY_API_KEY

如何读取由 Google 生成的 JSON 并将数据动态插入到响应变量中,以便每次通过开始和结束时计算距离和时间并将其显示给我?

【问题讨论】:

  • 我建议您在这种情况下使用 Google Maps JS API 而不是他们的网络服务。你可以找到它here。指导您的示例是here
  • 我使用 JS 但不工作,现在我使用 Web 服务及其工作

标签: json google-maps


【解决方案1】:

完成:

<?php 
$start= !empty($_GET['start']) ? urlencode($_GET['start']) : null;
$end = !empty($_GET['end']) ? urlencode($_GET['end']) : null;
$urlApi = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$start."&destinations=".$end."&key=API_KEY";
$result = file_get_contents($urlApi);
$data = json_decode($result, true);
$millas =  $data['rows'][0]['elements'][0]['distance']['text'];
$millasKm = round(($millas * 1.60934),2);
$duration = $data['rows'][0]['elements'][0]['duration']['text'];
?>
Distance: <?php echo $millasKm." Km";?><br>
Duration: <?php echo $duration;?><br>

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多