0

This is the alternative route function, while when I redirect with other direction. It can not clear the previous route.

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);
    }
});
}
geocodezip
  • 158,664
  • 13
  • 220
  • 245
Henning Lee
  • 544
  • 4
  • 13
  • related question: [Remove route google maps API using button](http://stackoverflow.com/questions/32290379/remove-route-google-maps-api-using-button) – geocodezip Sep 20 '15 at 08:18
  • related question: [Clearing multiple direction results of a google map](http://stackoverflow.com/questions/31706907/clearing-multiple-direction-results-of-a-google-map) – geocodezip Sep 20 '15 at 08:19
  • possible duplicate of [Google Maps JS API v3 - Simple Multiple Marker Example](http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) – EdChum Sep 20 '15 at 09:39
  • @geocodezip, thank you so much, hope it is not too late. – Henning Lee Sep 23 '15 at 16:46
  • @geocodezip, I remember used the global variables in javascript. Just like the directions = []; . Assign a new value to it in a function and read the variable again in another function. But the variable is always empty. How can you do that. Thank you – Henning Lee Sep 23 '15 at 16:51
  • @geocodezip if put "console.log(directions.length);" before "document.getElementById('submit').addEventListener". What it always show 0 in console panel. – Henning Lee Oct 06 '15 at 10:33
  • What is `directions`? I don't see that in the posted code... – geocodezip Oct 06 '15 at 13:43
  • @geocodezip Sorry, I meant your code below // in the global scope directions = []; – Henning Lee Oct 08 '15 at 04:09

1 Answers1

2

If you need to change/remove the rendered directions, you need to keep references to the google.maps.DirectionsRenderer objects that you use to display directions on the map and remove them from the map before losing that reference.

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);
});

code snippet:

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>
geocodezip
  • 158,664
  • 13
  • 220
  • 245