ViniBiso
ViniBiso

Reputation: 179

How to delete an old Route from a Map?

there. I have a marker on a map (Google Maps APIV3) where every time I change its position I calc a new route to the closest point on the map. And that is working fine, but also every time I change the position of the Marker the map is still keeping the old route. I tried everything and nothing worked. How do I delete and old Route from a Map?

You can see the problem on this link http://mercurio.cafw.ufsm.br/~grupo1/ If you move the blue marker, it works just fine. But if you move it again the old route is still there.

Here is the code!

var mapOptions = {
    center: new google.maps.LatLng(-27.357246,-53.396022),
    zoom: 14,
    maxZoom: 17,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}; 

var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
var marcador = new google.maps.LatLng(-27.355379,-53.397773);
var seuMarcador = new google.maps.Marker({
    position: marcador,
    map: map,
    icon: "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png",
    title:"Mova essa marcador para seu endereço.",
    draggable: true
});

 google.maps.event.addListener(seuMarcador, 'mouseup', function(event) {
var addr = new Array(5);
    addr[0] = new google.maps.LatLng(-27.352646,-53.384881);
    addr[1] = new google.maps.LatLng(-27.344648,-53.395009);
    addr[2] = new google.maps.LatLng(-27.365562,-53.388859);
    addr[3] = new google.maps.LatLng(-27.366241,-53.401655);
    addr[4] = new google.maps.LatLng(-27.360467,-53.397476);

    //var a = new google.maps.LatLng(-27.357837,-53.395661);
    var a = event.latLng;
    var menorDistancia;
    var destinoFinal;
    var directionsDisplay;
    directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);


    function calcRoute(inicio,fim) {
        var start = inicio;
        var end = fim;
        var request = {
            origin:start,
            destination:end,
            travelMode: google.maps.TravelMode.DRIVING
        };
        //I BELIVE THAT THE PROBLEM IS HERE
        var directionsService = new google.maps.DirectionsService();
        directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(result);
            }
        });
    }
});

Upvotes: 1

Views: 722

Answers (1)

geocodezip
geocodezip

Reputation: 161334

Don't create a new DirectionsRenderer for each call, reuse the same one. Remove this from your event listener:

directionsDisplay = new google.maps.DirectionsRenderer();

Upvotes: 1

Related Questions