Search code examples
javascriptgoogle-mapsgoogle-maps-api-3google-polyline

How to show Traffic layer on top of Directions polyline in google maps API


I am using the Javascript API to show a google map with directions (based on user input) along with the traffic layer. it works well, but i cannot figure out a way to show the traffic colors on the relevant polylines above my custom created line. what's the correct way to do this?


Solution

  • Displaying the Traffic Layer

    Simply displaying the traffic layer can be done using the JavaScript API like the following

    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);
    }
    

    This will not only give you access to the traffic layer, but also to the transit and bicycling layers as well.

    Here is a working example:

    <!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,
              center: {lat: 34.04924594193164, 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: before using it make sure you use your API KEY in

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

    For more information about this example you can read the documentation page regarding this example or the full documentation for displaying data (which i recomemend).

    This is not exactly what I want

    Experience usualy tells us that when you are suggesting a route to a user, if the said route has a red traffic line the user will automatically search for something else - forcing him to do another query would be cumbersome.

    Thus Traffic layers are a good solution to avoid the previous behavior.

    This however also means that you can't simply pick a part of the layer (say, the one matching your polyline) and paste it there - that is not the purpose of layers.

    If this solution is not good for you, there is another way...

    Directions Service

    The Directions Service which caluculates the directions between two points.

    With this Service, you can make a request with provideRouteAlternatives set to true and a departureTime set for drivingOptions.

    According to the documentation,

    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. (...)

    So if you make a request for alternative routes and have a departureTime you will have a duration_in_traffic in the reponse for each route, and with it you can draw the polygon with the colour you want depending on how good or bad the path is.

    You can read more about JavaScript Directions Service at https://developers.google.com/maps/documentation/javascript/directions

    This is still not what I want

    Using only Google Maps APIs and Services, this is as far as you can go. If these options still don't suit you then you will need to mix your map with traffic data from third-parties.


    Hope this helps!