Search code examples
javascriptloopshere-api

Every time i call this function the old markers are staying back and new markers are appearing is there any way to solve this?


created new linestring for previous polyline so new route is coming every time but markers are staying back! the for loop creates markers at manuver points.

https://i.sstatic.net/MeQ4h.jpg

function addManueversToMap(route){
      var svgMarkup = '<svg width="18" height="18" ' +
        'xmlns="http://www.w3.org/2000/svg">' +
        '<circle cx="8" cy="8" r="8" ' +
          'fill="#1b468d" stroke="white" stroke-width="1"  />' +
        '</svg>',
        dotIcon = new H.map.Icon(svgMarkup, {anchor: {x:8, y:8}}),

        i,
        j;

      // Add a marker for each maneuver
      for (i = 0;  i < route.leg.length; i += 1) {
        for (j = 0;  j < route.leg[i].maneuver.length; j += 1) {
          // Get the next maneuver.
          var maneuver = route.leg[i].maneuver[j];
          // Add a marker to the maneuvers group
          var marker =  new H.map.Marker({
            lat: maneuver.position.latitude,
            lng: maneuver.position.longitude} ,
            {icon: dotIcon});
          marker.instruction = maneuver.instruction;
          group.addObject(marker);
        }
      }

      group.addEventListener('tap', function (evt) {
        map.setCenter(evt.target.getGeometry());
        openBubble(
           evt.target.getGeometry(), evt.target.instruction);
      }, false);

      // Add the maneuvers group to the map
      map.addObject(group);
    }




Solution

  • You should remove previously added objects from the group.

    Just add group.removeAll() at the begining of the method addManueversToMap.

    Also, for better performance you should move code where you create svgMarkup and dotIcon out of this method.