Hi, I am trying to plan a route from the info window, but i am unable to remove the previous set route. I tried setMap(null) but it didn't work. I am using a callback for an event listener as i need to pass parameter which is returned from an api call. One option is to use new google.maps.map on each event e.g (link) on marker but than my markers are already placed when the page loads.
element = document.getElementById('map-canvas');
map = new google.maps.Map(element, options);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(car.lat, car.long),
map: map,
title: car.make
});
google.maps.event.addListener(marker, 'click', directionsCallback(car));
function directionsCallback(car) {
return function (e) {
if( infowindow != null ) {
infowindow.close();
}
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(null);
console.log(directionsDisplay);
calcRoute = function(){
var startPoint = document.getElementById('clientAddress').value;
var finishPoint = new google.maps.LatLng(car.lat, car.long);
var request = {
origin: startPoint,
destination: finishPoint,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
console.log(directionsDisplay)
console.log(response.routes.length)
infowindow.close();
}
else{
alert('Sorry ! ' + givenAddress + ' not recognized')
}
});
}
infowindow = new google.maps.InfoWindow();
infowindow.setContent("\n"
+ 'Directions to here : <input id = \'clientAddress\' placeholder=\"Postcode or City\" type=\'text\'>'
+ ' <input type=\'button\' onClick=calcRoute() value=\'Go!\'>')
infowindow.open(map, this);
}
}
define directionsDisplay only 1 time(outside of the click-handler)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With