javascripthere-api

How to show multiple map routes each being in different color using HERE Maps javascript?


I am new to HERE. I've been trying to show different routes on the same map (the coordinates and the colors are read from database). The routes are shown as expected, but only in the last color value of the color values array. How to make it show the different routes with different colors?

Here is my code (the initialization of the variables used prior to this code is omitted, only the code related to the map is posted):

    var map = new H.Map(document.getElementById('mapContainer'),
    defaultLayers.vector.normal.map,{
    center: {lat: 40, lng: 19},
     zoom: 7,
 

     pixelRatio: window.devicePixelRatio || 1

    });

    //map.setBaseLayer(defaultLayers.raster.satellite.map);
    window.addEventListener('resize', () => map.getViewPort().resize());
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
    var ui = H.ui.UI.createDefault(map, defaultLayers);
    
    for (var n = 0; n < sourceLatSplit.length; n++){
        var routingParameters = {
          'routingMode': 'fast',
          'transportMode': 'truck',
          'origin': sourceLatSplit[n].toString() + ',' + sourceLongSplit[n].toString(),
          'destination': destinationLatSplit[n].toString() + ',' + destinationLongSplit[n].toString(),
          'return': 'polyline'
        };
        routingParametersArray.push(routingParameters);
    }

    var onResult = function(result) {
        for (var r = 0; r < sourceLatSplit.length; r++){
            if (result.routes.length) {
        result.routes[0].sections.forEach((section) => {
            let linestring = H.geo.LineString.fromFlexiblePolyline(section.polyline);
            console.log(colorValuesSplit[r]);
            let routeLine = new H.map.Polyline(linestring, {
              style: { strokeColor: colorValuesSplit[r].toLowerCase(), lineWidth: 6 }
            });


        let startMarker = new H.map.Marker(section.departure.place.location);
        let endMarker = new H.map.Marker(section.arrival.place.location);
        var group = new H.map.Group();
        group.addObject(routeLine);
        console.log(group);

        group.addEventListener('tap', function (evt) {
        var bubble = new H.ui.InfoBubble(evt.target.getGeometry(), {
            content: evt.target.getData()
        });
            ui.addBubble(bubble);
        }, false);

        addMarkerToGroup(group, startMarker,
            '<div><b>'// + sourceLocationSplit[0] + 
                         +'</b></div><div><b>Latitude: </b>' + startMarker.getGeometry().lat + '</div><div><b>Longitude: </b>' + startMarker.getGeometry().lng + '</div>');

        addMarkerToGroup(group, endMarker,
            '<div><b>'// + destinationLocationSplit[0] + 
                         +'</b></div><div><b>Latitude: </b>' + endMarker.getGeometry().lat + '</div><div><b>Longitude: </b>' + endMarker.getGeometry().lng + '</div>');
        
        map.addObjects([group]);
        map.getViewModel().setLookAtData({bounds: routeLine.getBoundingBox()});

        });
    }} 
    };

    var router = platform.getRoutingService(null, 8);

    for (var i = 0; i < routingParametersArray.length; i++){
        
    
router.calculateRoute(routingParametersArray[i], onResult,
  function(error) {
    alert(error.message);
  });
    }
}

Solution

  • It is not related to HERE Maps Javascript issue. It is related to incorrect organized your code in callback onResult

    You need to remove the loop for (var r = 0; r < sourceLatSplit.length; r++){ from the callback onResult because callback onResult starts to run for each calculated route and it is enough.

    Then your code will be looks like:

        let r = 0;
        
            var onResult = function(result) {
                    //for (var r = 0; r < sourceLatSplit.length; r++){
                        if (result.routes.length) {
                    result.routes[0].sections.forEach((section) => {
                        let linestring = H.geo.LineString.fromFlexiblePolyline(section.polyline);
                        console.log(colorValuesSplit[r]);
                        let routeLine = new H.map.Polyline(linestring, {
                          style: { strokeColor: colorValuesSplit[r].toLowerCase(), lineWidth: 6 }
                        });
    r++;
    

    But keep in mind that if some response of request of route will be delayed then you will get always different colors for the same polylines(when you run your completely code again and again), i.e. the order of the colors will not match to order of defined routes.

    To resole it you need apply a bind to function onResult like: router.calculateRoute(routingParametersArray[i], onResult.bind({r: i}) then in function onResult you can get this r: this.r

    like:

    var onResult = function(result) {
            //for (var r = 0; r < sourceLatSplit.length; r++){
                if (result.routes.length) {
            result.routes[0].sections.forEach((section) => {
                let linestring = H.geo.LineString.fromFlexiblePolyline(section.polyline);
                console.log(colorValuesSplit[this.r]);
                let routeLine = new H.map.Polyline(linestring, {
                  style: { strokeColor: colorValuesSplit[this.r].toLowerCase(), lineWidth: 6 }
                });