javascript - 使用 JS 和 HTML 的 Google map API(从地点 A 到地点 b 的方向)

标签 javascript html json google-maps google-maps-api-3

我想做:

  1. 获取从地点 A 到地点 B 的路线
  2. 这两个地方之间的距离
  3. 以及持续时间(交通情况下)

因此我有以下代码

var request = {
        origin:location1, 
        destination:location2,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,


    };
    directionsService.route(request, function(response, status) 
    {
        if (status == google.maps.DirectionsStatus.OK) 
        {
            directionsDisplay.setDirections(response);
            distance = "Die Entfernung zur Arbeit entspricht: "+ "<b>" +response.routes[0].legs[0].distance.text +"</b>";
            distance += "<br/>Die vorausschauliche Fahrzeit betr&auml;gt: "+ "<b>"+response.routes[0].legs[0].duration_in_traffic.text +"</b>";
            document.getElementById("distance_road").innerHTML = distance;
        }

    });

在此代码示例中,我无法获取“duration_in_traffic”。我认为这是因为我没有高级计划?

所以我在想别的办法。这个 URL 给我一个 JSON 对象作为响应。此 JSON 对象包括 period_in_traffic。

https://maps.googleapis.com/maps/api/directions/json?origin=Bellheim&destination=Voeklingen&departure_time=now&key=MYKEY

但是我不知道如何在javascript中获取json对象,也不知道如何从json对象中提取信息。

你能帮我解决这个问题吗?

最佳答案

查看此处提供的文档,我假设您收到以下内容 JSON :

{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361715
               },
               "duration" : {
                  "text" : "3 hours 49 mins",
                  "value" : 13725
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

如果上面的响应,那么您可以使用 <var_name>.rows.elements.distance 来获取距离

<小时/>

After looking at your image

<小时/>

您可以访问您的distance_in_traffic使用:<var_name>.routes.0.legs.0.distance.<text/value>

关于javascript - 使用 JS 和 HTML 的 Google map API(从地点 A 到地点 b 的方向),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44259409/

相关文章:

javascript - 防止 "bubbling"?

javascript - 轨道控制跟随鼠标,无需点击 Three.js

javascript - wrapAll() 只处理第一个元素?

PHP 和 Javascript 文档生成器

javascript - 在给定时间间隔内调整图像大小的 Web 技术

javascript - .php 脚本的 Ajax 请求被取消

javascript - 无法使用 jquery $.ajax 访问从 php 页面检索的 json 数据

javascript - 如何缩放内容以保持比例

Python:将多个 YAML 文档转换为 JSON

c++ - 使用 rapidjson 读取嵌套的 Json