Clear a route between two points (API google maps)

Asked

Viewed 520 times

0

I created a system of routes between two points in Google Maps (one passed by the user and the other already defined by me). My problem is in the process of showing a new route, that is, how can I remove a route previously mapped by the user, to provide a new route if he does the search again?

I already used "directionsDisplay.setMap(null);" but I did not get results....

 /// INITIALIZATE MAP
    // Iniciando variaveis
    var geocoder;
    var map;
    var marker = '../../imagens/assets/marker-blue.png';
    var directionsService = new google.maps.DirectionsService();

    // Iniciando o map
    function initialize() {
        var latlng = new google.maps.LatLng(-18.898123, -48.265920);
        var options = {
            zoom: 18,
            center: latlng,
            mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
        };
        map = new google.maps.Map(document.getElementById("mapa"), options);
        geocoder = new google.maps.Geocoder();

        // Marcador Personalizado
        marker = new google.maps.Marker({
            map: map,
            animation: google.maps.Animation.DROP,
            icon: marker
        });
        marker.setPosition(latlng);

        // Parâmetros do texto que será exibido no clique;
        var contentString =
            '<h2 class="tip-title">Sertões PetShop</h2>' +
            '<p class="tip-text">Av. Brasil, 2909 - B. Brasil</p>' +
            '<p class="tip-text">Uberlândia-MG</p>' +
            '<a class="tip-site"href="http://www.marcozeropetshop.com.br" target="_blank">www.sertoespetshop.com.br</a>';
        var infowindow = new google.maps.InfoWindow({
            content: '<div id="scrollFix">' + contentString + '</div>',
            maxWidth: 700
        });

        // Exibir texto ao clicar no ícone;
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
        });

        // Infowindow delay
        setTimeout(function() {
            infowindow.open(map, marker);
        }, 1700);

    }

    initialize();

    // CARREGANDO O MAPA
    function carregarNoMapa(endereco) {
        geocoder.geocode({
                'address': endereco,
                'region': 'BR',
                'componentRestrictions': {
                    'country': 'BR',
                    'administrativeArea': 'Uberlândia'
                }
            },

            function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        var latitude = results[0].geometry.location.lat();
                        var longitude = results[0].geometry.location.lng();

                        $('#txtEndereco').val(results[0].formatted_address);
                        $('#txtLatitude').val(latitude);
                        $('#txtLongitude').val(longitude);

                        var location = new google.maps.LatLng(latitude, longitude);
                        marker.setPosition(location);
                        map.setCenter(location);
                        map.setZoom(16);
                    }
                }
            });
    }

    // CAPTURANDO AS POSIÇÕES E RESULTANDO
    google.maps.event.addListener(marker, 'drag', function() {
        geocoder.geocode({
            'latLng': marker.getPosition()
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    $('#txtEndereco').val(results[0].formatted_address);
                    $('#txtLatitude').val(marker.getPosition().lat());
                    $('#txtLongitude').val(marker.getPosition().lng());
                }
            }
        });
    });

    // Autocomplete dinâmico
    $("#txtEndereco").autocomplete({
        source: function(request, response) {

            geocoder.geocode({
                    'address': request.term + ', Brasil',
                    'region': 'BR',
                    'componentRestrictions': {
                        'country': 'BR',
                        'administrativeArea': 'Uberlândia'
                    }
                },

                function(results, status) {
                    response($.map(results, function(item) {
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            latitude: item.geometry.location.lat(),
                            longitude: item.geometry.location.lng()
                        };
                    }));
                });
        },
    });

    // Obtendo a latitude e longitude
    $("#btnEndereco").click(function() {

        var directionsDisplay = new google.maps.DirectionsRenderer();
        var request = {
            origin: $("#txtEndereco").val(),
            destination: new google.maps.LatLng(-18.898123, -48.265920),
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                var leg = response.routes[0].legs[0];

                var mStart = new google.maps.Marker({
                    icon: '../../imagens/assets/marker-green.png',
                    position: leg.start_location,
                    map: map,
                });

                var mEnd = new google.maps.Marker({
                    icon: '../../imagens/assets/marker-blue.png',
                    position: leg.end_location,
                    map: map
                });

                // MARCADOR RETURN SHOW
                var contentString = '<h2 class="tip-title">Sertões PetShop</h2>' +
                    '<p class="tip-text">Av. Brasil, 2909 - B. Brasil</p>' +
                    '<p class="tip-text">Uberlândia-MG</p>' +
                    '<a class="tip-site"href="http://www.marcozeropetshop.com.br" target="_blank">www.sertoespetshop.com.br</a>';
                var infowindow = new google.maps.InfoWindow({
                    content: '<div id="scrollFix">' + contentString + '</div>',
                    maxWidth: 700
                });

                // Exibir texto ao clicar no ícone;
                google.maps.event.addListener(mEnd, 'click', function() {
                    infowindow.open(map, mEnd);
                });

                // Infowindow delay
                setTimeout(function() {
                    infowindow.open(map, mEnd);
                }, 1700);

                marker.setMap(null);

                directionsDisplay.setDirections(response);
                directionsDisplay.setOptions({
                    suppressMarkers: true,
                    polylineOptions: {
                        strokeWeight: 6,
                        strokeOpacity: 0.7,
                        strokeColor: '#0C47A0'
                    }
                });
                directionsDisplay.setMap(map);
            }
        });

    });

    // Realizando a busca depois do clique
    $("#form-location").submit(function(event) {
        event.preventDefault();
        var endereco = $("#txtEndereco").val();
        var latitude = $("#txtLatitude").val();
        var longitude = $("#txtLongitude").val();
    });
  • What takes the route is even the "directionsDisplay.setMap(null);", I have running in a project. In which part of the code you tried to put?

  • After the click action, before starting the object that takes the routes.

1 answer

0


You must store the directionsDisplay object in a variable if it is set from setMap(null).

//variavel para guardar o directionsDisplay
var displayObject = false;

// Obtendo a latitude e longitude
$("#btnEndereco").click(function() {

    //se a variavel estiver setada
    if(displayObject){
        displayObject.setMap(null);
    }

    var directionsDisplay = new google.maps.DirectionsRenderer();
    var request = {
        origin: $("#txtEndereco").val(),
        destination: new google.maps.LatLng(-18.898123, -48.265920),
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {

            var leg = response.routes[0].legs[0];

            var mStart = new google.maps.Marker({
                icon: '../../imagens/assets/marker-green.png',
                position: leg.start_location,
                map: map,
            });

            var mEnd = new google.maps.Marker({
                icon: '../../imagens/assets/marker-blue.png',
                position: leg.end_location,
                map: map
            });

            // MARCADOR RETURN SHOW
            var contentString = '<h2 class="tip-title">Sertões PetShop</h2>' +
                '<p class="tip-text">Av. Brasil, 2909 - B. Brasil</p>' +
                '<p class="tip-text">Uberlândia-MG</p>' +
                '<a class="tip-site"href="http://www.marcozeropetshop.com.br" target="_blank">www.sertoespetshop.com.br</a>';
            var infowindow = new google.maps.InfoWindow({
                content: '<div id="scrollFix">' + contentString + '</div>',
                maxWidth: 700
            });

            // Exibir texto ao clicar no ícone;
            google.maps.event.addListener(mEnd, 'click', function() {
                infowindow.open(map, mEnd);
            });

            // Infowindow delay
            setTimeout(function() {
                infowindow.open(map, mEnd);
            }, 1700);

            marker.setMap(null);

            directionsDisplay.setDirections(response);
            directionsDisplay.setOptions({
                suppressMarkers: true,
                polylineOptions: {
                    strokeWeight: 6,
                    strokeOpacity: 0.7,
                    strokeColor: '#0C47A0'
                }
            });
            directionsDisplay.setMap(map);

            //depois de setar o directionsDisplay guardar na variavel
            displayObject = directionsDisplay;
        }
    });

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.