Jyotirmay
Jyotirmay

Reputation: 1825

How to show real time traffic data for a particular route on maps

I have implemented direction API to find out a route from source to destination using Google Maps V3 direction API in browser/JavaScript.

Now I want to display traffic situation as shown in below snapshot (snapshot from google maps) in the route part only.

enter image description here

Is there a way to do so with different polyline strokeColor for different level of traffic condition?

If it is not possible using direction API or traffic layer, can I make use of the premium version of direction matrix or road API to implement this?

Below is what I have done until now and my output accordingly:

  var map;
  var directionsService;
  var polyline;
  var directionsDisplay;
  function initMap() {
    directionsDisplay = new google.maps.DirectionsRenderer({
      polylineOptions:{
        strokeOpacity:1,
        strokeWeight:5,
        strokeColor: 'green'
      },
      draggable: true
    });

    directionsService = new google.maps.DirectionsService;
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 14,
      center: {lat: 37.77, lng: -122.447}
    });

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

    directionsDisplay.setMap(map);
               directionsDisplay.setPanel(document.getElementById('directionsPanel'));

    directionsDisplay.addListener('directions_changed', function() {
      DistanceOut(directionsDisplay.getDirections());
    });
    polyline = new google.maps.Polyline({
      map:map
    });
    calculateAndDisplayRoute(directionsService, directionsDisplay);

  }

  function calculateAndDisplayRoute(directionsService,    directionsDisplay) {

    directionsService.route({
      origin: 'Whitefield, Bangalore',
      destination: 'Indira nagar, Bangalore',

      provideRouteAlternatives: true,
      travelMode: 'DRIVING',
      drivingOptions: {
        departureTime: new Date(Date.now()),
        trafficModel: 'bestguess'
      },
      unitSystem: google.maps.UnitSystem.METRIC

    }, function(response, status) { console.log(response);
      if (status == 'OK') {
        directionsDisplay.setDirections(response);
        DistanceOut(response);
        changeStepColor(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

  function DistanceOut(response){
    document.getElementById("travelDetail").innerHTML = "Distance:"+response.routes[0].legs[0].distance.text+
        "<br> Duration::"+response.routes[0].legs[0].duration.text+
        "<br> Duration in traffic::"+response.routes[0].legs[0].duration_in_traffic.text;
  }

  // Here I want to change the polyline color according to the traffic condition.
  // Can I? Or if any other way to do so?!
  function changeStepColor(res){
    var steps = res.routes[0].legs[0].steps;

    for(i=0; i<steps.length; i++){
      if((steps[i].distance.value/steps[i].duration_in_traffic.value) > 5) {
        //steps[i].polyline.strokeColor='blue';
        //directionsDisplay.setOptions({polylineOptions: {path: steps[i].path ,strokeColor: 'red'}});
      } else {
        //directionsDisplay.setOptions({polylineOptions: {path: steps[i].path ,strokeColor: 'yellow'}});

        //steps[i].polyline.strokeColor='red'
      }
    }
  }

Here is my Output snapshot: enter image description here

I hope this helps you to understand my issue. Let me know if anything else is needed to understand my issue.

Upvotes: 4

Views: 9739

Answers (3)

chisom onwuegbuzie
chisom onwuegbuzie

Reputation: 457

import Polyline from '@mapbox/polyline';

const origin = `${currentPosition.latitude}, ${currentPosition.longitude}`; 
const destination = `${User.latitude}, ${User.longitude}`; 

try {
    const waypoints = this.outletCoordinates.map(waypoint => 
      `${waypoint.latitude},${waypoint.longitude}`).join('|');
    const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&waypoints=optimize:true|${waypoints}&key=${Config.GOOGLE_MAPS_API_KEY}&mode=DRIVING`;

    const mapUrl = await fetch(url); 
    const respJson = await mapUrl.json();
    const routes = _.get(respJson, 'routes', []);
    if (routes.length > 0 && routes[0]) {
        const routeDescrip = routes[0]; 
        const [summaryLeg] = routeDescrip.legs || []; 
        const points = Polyline.decode(routeDescrip.overview_polyline.points); 
        const optimizedRoutes = points.map(point => ({
          latitude: point[0],
          longitude: point[1],
        }));
    }
}

Upvotes: 1

xomena
xomena

Reputation: 32178

Currently there is no possibility to display traffic only for a route using the Google Maps JavaScript API directions service. You can show traffic for entire city via Traffic layer, but not for single streets.

Premium plan license doesn't matter, you will have the same output for directions. Other APIs like Roads API and Distance Matrix API do not provide any traffic related information in responses.

The feature request has been filed in Google issue tracker:

https://issuetracker.google.com/issues/36537583

Feel free to star the feature request to add your vote and subscribe to notifications from Google.

UPDATED

It looks like Embed API shows traffic information for the route. Try to use Embed API in directions mode. This will give you something like

enter image description here

Upvotes: 6

arde
arde

Reputation: 116

If I understand your question correctly, you want to provide real time traffic data to a route that has been built. First off , in order to do this, you will need a Google Maps Premium Plan client ID. In order to display traffic information to a route, you will need to implement a Directions Request. Previous you could use a durationInTraffic but that has since been deprecated. You must now use the drivingOptions which can then be applied to your custom polyline.

Upvotes: 3

Related Questions