微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在Google maps API中显示路线折线顶部的流量图层

我正在使用 Javascript API来显示带有路线(基于用户输入)的Google地图以及流量层.它工作得很好,但是我无法找出一种在自定义创建行上方的相关折线上显示流量颜色的方法.这样做的正确方法是什么?

解决方法

显示流量层

简单地显示流量层可以使用如下的JavaScript API来完成

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'),{
    zoom: 13,center: {lat: 34.04924594193164,lng: -118.24104309082031}
  });

  var trafficLayer = new google.maps.TrafficLayer();
  trafficLayer.setMap(map);
}

这不仅可以让您访问流量层,还可以访问交通和自行车层.

这是一个工作示例:

<!DOCTYPE html>
<html>
  <head>
    <Meta name="viewport" content="initial-scale=1.0,user-scalable=no">
    <Meta charset="utf-8">
    <title>Traffic layer</title>
    <style>
      html,body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'),{
          zoom: 13,lng: -118.24104309082031}
        });

        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map);
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

PS:在使用之前,请确保使用您的API KEY

<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
        </script>

有关此示例的更多信息,您可以阅读documentation page regarding this example或完整的documentation for displaying data(我推荐).

这不是我想要的

经验告诉我们,当您向用户建议路由时,如果所述路由具有红色流量线,用户自动搜索其他内容,迫使他执行其他查询将是麻烦的.

因此,流量层是避免以前行为的一个很好的解决方案.

这也意味着您不能简单地选择图层的一部分(例如,与折线匹配的部分)并将其粘贴到那里 – 这不是图层的目的.

如果这个解决方案不适合你,还有另一种方法

方向服务

Directions Service校准两点之间的方向.

使用此服务,您可以将provideRoutealternatives设置为true并为drivingOptions设置一个出发时间进行请求.

根据文件,

departureTime (required for the drivingOptions object literal to be
valid) specifies the desired time of departure as a Date object. (…)
For Google Maps APIs Premium Plan customers,if you include the
departureTime in the request,the API returns the best route given the
expected traffic conditions at the time,and includes the predicted
time in traffic (duration_in_traffic) in the response. (…)

所以如果你要求替代路线,并且有一个出发时间,你将有一个duration_in_traffic在每个路线的响应,并且它可以绘制多边形与您想要的颜色,取决于路径的好坏.

您可以在https://developers.google.com/maps/documentation/javascript/directions阅读有关JavaScript Directions Service的更多信息

这还不是我想要的

只使用Google Maps API和服务,这是尽可能远的.如果这些选项仍然不适合您,则需要将地图与来自第三方的流量数据进行混合.

希望这可以帮助!

原文地址:https://www.jb51.cc/js/152804.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐