10

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?

kob490
  • 3,177
  • 4
  • 25
  • 40

2 Answers2

6

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!

Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266
  • 1
    Better if i get the traffic only for the selected source and destination's path – Shashank Sood Sep 16 '16 at 04:36
  • This is not exactly what question is asked for. How to display traffic color on a selected direction from a source to destination. Like how google maps display when you search for a route from one place to another. – Jyotirmay Jan 13 '17 at 19:02
  • @Jyotirmay I beg to differ. This is the closest thing he can get to what he wants, given the current state of the Maps API. I believe downvoting my answer is harsh at best, given the effort and time put into it and the range of possibilities available. – Flame_Phoenix Jan 15 '17 at 13:33
2

Try to use Embed API in directions mode. Details about it you can find it here (Embed API in Direction mode). Here is an example which looks like this.

  <iframe
    width="600"
    height="450"
    frameborder="0" style="border:0"
    src="https://www.google.com/maps/embed/v1/directions?key=YOUR_API_KEY&origin=indira+nagar+Bangalore&destination=Whitefield+Bangalore&avoid=tolls|highways" allowfullscreen>
  </iframe>

Which will give you below output.

enter image description here

You can generate src URL dynamically for run time source - destination traffic route display.

Jyotirmay
  • 1,533
  • 3
  • 21
  • 41
  • 1
    Thanks for the tip - this is exactly what I wanted! – Nicholas Apr 20 '18 at 02:36
  • 1
    Thanks for the method @Jyotirmay, it works well for us, too. But we found that if waypoints are added there will be no traffic color. Don't know if this is a bug or just intended by Embeded API. Is there any way to workaround this? – YGLin Nov 21 '18 at 06:53
  • 1
    hey @YGLin, I am sorry, but I worked on it long back and literally forget everything as of now. You need to do more research from your side. :) I am no help for this now. Please upvote, if this answer helps you in any manner. :) Thanks. – Jyotirmay Nov 21 '18 at 10:37