2015-09-20 2 views
-1

Это альтернативная функция маршрута, а когда я перенаправляюсь в другом направлении. Он не может очистить предыдущий маршрут.API Google MAP V3 не может очистить историю предыдущих маршрутов.

function initialize() { 

// Create a new map with some default settings 
var myLatlng = new google.maps.LatLng(-37.8602828,145.079616); 
var myOptions = { 
    zoom:8, 
    center: myLatlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
} 
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

//click function call calculateAndDisplayRoute to ge the alternative routes 
     var directionsService = new google.maps.DirectionsService; 



     document.getElementById('submit').addEventListener('click', function() { 

      calculateAndDisplayRoute(directionsService, map); 

     }); 


//this function used to calculate the alternative route. 
function calculateAndDisplayRoute(directionsService, map) {  

//get the value from start and end input box 
var start = document.getElementById('start').value; 
var end =document.getElementById('end').value; 

//property when dran on the map 
var directionsRequest = { 
    //starting point 
    origin: start, 
    //destination 
    destination: end, 
    //multiple route 
    provideRouteAlternatives: true, 
    travelMode: google.maps.TravelMode.DRIVING 

}; 

directionsService.route(directionsRequest, function(response, status) { 

    if (status === google.maps.DirectionsStatus.OK) { 
     //store the multiple routes in respones and display one by one 
     for (var i = 0, len = response.routes.length; i < len; i++) { 
       new google.maps.DirectionsRenderer({ 
       map: map, 
       directions: response, 
       routeIndex: i 
       }); 
     } 

    } else { 
     window.alert('Directions request failed due to ' + status); 
    } 
}); 
} 
+0

связанный с этим вопрос: [Удалить маршрут Google Maps API с помощью кнопки] (http://stackoverflow.com/ вопросы/32290379/remove-route-google-maps-api-using-button) – geocodezip

+0

Связанный вопрос: [Cl (http://stackoverflow.com/questions/31706907/clearing-multiple-direction-results-of-a-google-map) – geocodezip

+0

Возможный дубликат [Google Maps JS API v3 - Простой Пример нескольких маркеров] (http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) – EdChum

ответ

2

Если вам необходимо изменить/удалить визуализированную направления, вы должны держать ссылки на google.maps.DirectionsRenderer объектов, которые используются для отображения направления на карте и удалить их с карты, прежде чем потерять эту ссылку.

proof of concept fiddle

// in the global scope 
directions = []; 

document.getElementById('submit').addEventListener('click', function() { 
if (directions && directions.length > 0) { 
    for (var i=0; i<directions.length; i++) 
    directions[i].setMap(null); 
    } 
    directions = []; 
    calculateAndDisplayRoute(directionsService, map); 
}); 

фрагмент кода:

var directions = []; 
 

 
function initialize() { 
 

 
    // Create a new map with some default settings 
 
    var myLatlng = new google.maps.LatLng(-37.8602828, 145.079616); 
 
    var myOptions = { 
 
    zoom: 8, 
 
    center: myLatlng, 
 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
 
    } 
 
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
 

 
    //click function call calculateAndDisplayRoute to ge the alternative routes 
 
    var directionsService = new google.maps.DirectionsService; 
 

 

 

 
    document.getElementById('submit').addEventListener('click', function() { 
 
    if (directions && directions.length > 0) { 
 
     for (var i = 0; i < directions.length; i++) 
 
     directions[i].setMap(null); 
 
    } 
 
    directions = []; 
 
    calculateAndDisplayRoute(directionsService, map); 
 

 
    }); 
 

 

 
    //this function used to calculate the alternative route. 
 
    function calculateAndDisplayRoute(directionsService, map) { 
 

 
    //get the value from start and end input box 
 
    var start = document.getElementById('start').value; 
 
    var end = document.getElementById('end').value; 
 

 
    //property when dran on the map 
 
    var directionsRequest = { 
 
     //starting point 
 
     origin: start, 
 
     //destination 
 
     destination: end, 
 
     //multiple route 
 
     provideRouteAlternatives: true, 
 
     travelMode: google.maps.TravelMode.DRIVING 
 

 
    }; 
 

 
    directionsService.route(directionsRequest, function(response, status) { 
 

 
     if (status === google.maps.DirectionsStatus.OK) { 
 
     //store the multiple routes in respones and display one by one 
 
     for (var i = 0, len = response.routes.length; i < len; i++) { 
 
      directions.push(new google.maps.DirectionsRenderer({ 
 
      map: map, 
 
      directions: response, 
 
      routeIndex: i 
 
      })); 
 
     } 
 

 
     } else { 
 
     window.alert('Directions request failed due to ' + status); 
 
     } 
 
    }); 
 
    } 
 
} 
 
google.maps.event.addDomListener(window, "load", initialize);
html, 
 
body, 
 
#map_canvas { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0px; 
 
    padding: 0px 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<input type="button" value="get directions" id="submit" /> 
 
<input value="New York, NY" id="start" /> 
 
<input value="Newark, NJ" id="end" /> 
 
<div id="map_canvas"></div>

Смежные вопросы