How to route through multiple points google maps api?

Please help with this problem:
When you build a route between two locations, everything works correctly(remove markers by clicking on them, drag&drop works and the route is rebuilt)
If you add a new marker, it does not remove the previous and not to move them, the code works too. But if you put on the map and 3 more tokens, then if you start to move them, or remove the float bugs.

I think that in the code somewhere there is a logical error.
Here is my code:

var map;
 var markerArr = [];

 var directionsDisplay;
 var directionsService;

 function initMap() {

 map = new google.maps.Map(document.getElementById('map'), {
 center: {lat: 50.45466, lng: 30.5238},
 zoom: 8
});

 google.maps.event.addListener(map, 'click', function(e) {
 placeMarker(e.latLng, map); 
});

}


 routing function() {
 directionsDisplay = new google.maps.DirectionsRenderer();
 directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
 directionsDisplay.setOptions( { suppressMarkers: true, suppressInfoWindows: true } );

 for (let index = 0; index < markerArr.length; index++) {
 if (index>=1) {
 var request = {
 origin: new google.maps.LatLng(markerArr[index-1].position.lat(), markerArr[index-1].position.lng()), //starting point
 destination: new google.maps.LatLng(markerArr[index].position.lat(), markerArr[index].position.lng()), //the point of the finish
 travelMode: google.maps.DirectionsTravelMode.DRIVING //mode routing
};

 directionsService.route(request, function(response, status) {
 if (status == google.maps.DirectionsStatus.OK) { 
directionsDisplay.setDirections(response);
}
});
}

}
}

 function placeMarker(position, map) {
 var marker = new google.maps.Marker({
 position: position,
 map: map,
 draggable: true
 }); 

 var r1 = google.maps.event.addListener(marker,"click", removeMarkers.bind(null,position.lat()), false);

 google.maps.event.addListener(marker, 'dragend', function(marker) {
google.maps.event.removeListener(r1);
directionsDisplay.setMap(null);
remMarker(marker.latLng.lat());
routing();
});

 remMarker function(params) {
 google.maps.event.addListener(marker,"click", removeMarkers.bind(null,params), false);
}

markerArr.push(marker);
//console.log(markerArr[0].position.lat());
map.panTo(position);
console.log(markerArr);
routing();

}

 function removeMarkers(pos){
 for(let i=0; i<markerArr.length; i++){
 if (markerArr[i].position.lat() == pos) {
markerArr[i].setMap(null);
 markerArr = markerArr.filter(elem => elem.map != null);
}

}

console.log(markerArr);
directionsDisplay.setMap(null);
routing();
 }
April 4th 20 at 00:44
0 answer

Find more questions by tags Google Maps