3

Google map directionsService.route необходимо добавить удалить waypoint используя javascript.Объект массива Javascript необходимо удалить элемент

Можно добавить новую точку в массиве с помощью кода:

waypts.push({ location: "Rome, Italy", stopover: true }); 

Проблема, когда удалить путевую точку из массива

Вот мой пример некоторые данные, которые могут объяснить более кратко;

Необходимо удалить точку 1 или точку 2 из массива объектов javascript, как это возможно.

Затем я создам новые путевые путевки для каждого маршрута времени, следующего из массива с именем nwaypts.

var nwaypts = [ 
{ location: "Rome, Italy", stopover: true }, // xyz: start point 
{ location: { lat: 42.2070007, lng: 12.48549939999998 }, stopover: true, id: "17167" }, // point 1 
{ location: { lat: 42.3793831, lng: 12.82857039999999 }, stopover: true, id: "18823" }, // point 2 
{ location: "Terni, Italy", stopover: true } // xyz: end point 
]; 

ответ

2

Здравствуйте В удалить путевые точки, которые можно добавить идентификатор к маркеру, а затем в течение removecode и можно попытаться сравнить с маркерным идентификатором (который и хочет удалить) , Пожалуйста, предоставьте полный код, чтобы получить точное решение.

var nwaypts=[]; 
         var j=0; 
         for (var i = 0; i < waypts.length ; i++) { 
          if(waypts[i].id!=removemarkerid){ 
           nwaypts[j]=waypts[i]; 
           j++; 
          } 
         } 
         waypts=nwaypts; 
2

было несколько проблем с вами кодом. Рабочего примера находится в https://jsfiddle.net/z1dvs5wp/

Объяснения в коде:

<script> 

    // set variables outside initMap() function to make them visible for other functions 
    var waypts = []; 
    var directionsService; 
    var directionsDisplay; 
    var map; 

    // add waypoints 
    waypts.push({ 
     location: "winnipeg, mb", 
     stopover: true 
     }); 
    waypts.push({ 
     location: "spokane, wa", 
     stopover: true 
     });  

    function initMap() { 
    // map setup 
    directionsService = new google.maps.DirectionsService; 
    directionsDisplay = new google.maps.DirectionsRenderer; 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 6, 
     center: {lat: 41.85, lng: -87.65} 
    }); 
    directionsDisplay.setMap(map); 

    // calculate route 
    calculateAndDisplayRoute(directionsService, directionsDisplay); 
    } 

    function calculateAndDisplayRoute(directionsService, directionsDisplay) { 
    directionsService.route({ 
     origin:"Boston, MA",//document.getElementById('start').value, 
     destination: "San Francisco, CA",//document.getElementById('end').value, 
     waypoints: waypts, 
     optimizeWaypoints: true, 
     travelMode: 'DRIVING' 
    }, function(response, status) { 
     if (status === 'OK') { 
     directionsDisplay.setDirections(response); 
     var route = response.routes[0]; 
     var summaryPanel = document.getElementById('directions-panel'); 
     summaryPanel.innerHTML = ''; 
     // For each route, display summary information. 
     for (var i = 0; i < route.legs.length; i++) { 
      var routeSegment = i + 1; 
      summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + 
       '</b><br>'; 
      summaryPanel.innerHTML += route.legs[i].start_address + ' to '; 
      summaryPanel.innerHTML += route.legs[i].end_address + '<br>'; 
      summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>'; 
     } 
     } else { 
     window.alert('Directions request failed due to ' + status); 
     } 
    }); 
    } 

function removewaypoint(idx=0) { 
    // this function takes index of location to remove 
    // point A is start 
    // point B has index 0 
    // point C has index 1... 
    // removewaypoint(1) - will remove point C 

    waypts.splice(idx, 1); 

    // recalculate route with new waypoints 
    calculateAndDisplayRoute(directionsService, directionsDisplay); 
} 
</script> 
Смежные вопросы