【问题标题】:Goole Maps API (Direction from place A to place b) with JS and HTML带有 JS 和 HTML 的 Google Maps API(从 A 地到 B 地的方向)
【发布时间】:2017-10-30 18:16:34
【问题描述】:

我想做:

  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 对象包括 duration_in_traffic。

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

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

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

【问题讨论】:

  • quota plans 表示您可以使用 API 进行距离计算。
  • 我知道但不知道duration_in_traffic?
  • 您提到您可以在JSON 中获得distance_in_traffic。你能提供JSON吗?
  • @SreetamDas 正如你在我最近的回放中看到的那样(见图)
  • 哪张照片?

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


【解决方案1】:

查看此处提供的文档,我假设您收到以下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"
}

如果上面的响应,那么你可以通过&lt;var_name&gt;.rows.elements.distance得到距离


看完你的照片


您可以使用&lt;var_name&gt;.routes.0.legs.0.distance.&lt;text/value&gt; 访问您的distance_in_traffic

【讨论】:

  • @OP,这应该会有所帮助,假设JSON的性质
  • 首先谢谢您! :) 我的问题是: 1. 我不知道如何用 JS 获取这个 JSON 2. 我不知道如何使用你的答案
  • 你能把你当前使用的粘贴到this fiddle here吗?
猜你喜欢
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多