Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove previous Directions Route Google Maps

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


    }
}
like image 351
kam bajwa Avatar asked Sep 25 '26 09:09

kam bajwa


1 Answers

define directionsDisplay only 1 time(outside of the click-handler)

like image 171
Dr.Molle Avatar answered Sep 26 '26 21:09

Dr.Molle