Answer the question
In order to leave comments, you need to log in
How to get route through multiple points google maps api?
Please help with this problem:
When building a route between two points, everything works correctly (markers are deleted by clicking on them, drag & drop works and the route is rebuilt)
If you add new markers, while not deleting the previous ones and not moving them, then the code also works. But if you put 3 or more markers on the map, then if you start moving them, or delete them, bugs pop up.
I think there is a logical error somewhere in the code.
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);
});
}
function routing() {
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()), //точка старта
destination: new google.maps.LatLng(markerArr[index].position.lat(), markerArr[index].position.lng()), //точка финиша
travelMode: google.maps.DirectionsTravelMode.DRIVING //режим прокладки маршрута
};
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();
});
function remMarker(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();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question