Remove rendered direction routes on google map

2020-05-06 12:13发布

I try to render direction route on google map and my issue was, when I am try to get another direction route previously rendered route not clear. I want to know how I reset rendered route on the map.

Here my code.

function direction(dest, lat, lng) {

$('#direction').slideUp();
$('#results').slideDown();
$('#dest-direction').val(dest);


$('#direction-form').submit(function () {

    var ori = $('#origin-direction').val();

    map.setZoom(7);
    var currentLatLng = new google.maps.LatLng(lat, lng);
    map.setCenter(currentLatLng);

    var directionsRenderer = new google.maps.DirectionsRenderer();
    directionsRenderer.setMap(map);
    directionsRenderer.setPanel(document.getElementById('direction'));

    var directionsService = new google.maps.DirectionsService();

    /////////////////////
    default_unit_system = google.maps.UnitSystem.METRIC;
    if (current_unit == "km") {
        default_unit_system = google.maps.UnitSystem.METRIC;
    } else if (current_unit == "miles") {
        default_unit_system = google.maps.UnitSystem.IMPERIAL;
    }
    /////////////////////

    var request = {
        origin: ori,
        destination: lat+','+lng,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: default_unit_system
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsRenderer.setDirections(response);
        } else {
            //alert('Error: ' + status);
            $('#direction').append('<table width="100%"><tr><td>Direction not found. Please try again.</td></tr></table>');
        }
    });

    $('#direction-form').nextAll().remove();
    return false;

});

}

2条回答
孤傲高冷的网名
2楼-- · 2020-05-06 12:35

I agree with Dr.Molle .

Still, One thing that can be useful for many overlays (like markers, like infowindows, ...): Store the objects in an array; if needed, keep that array on the global scope; then you can easily remove them from the map.

var renderObjects = [];

function clearRenderObjects() {
  for(var i in renderObjects) {
    renderObjects[i].setMap(null);
  }
}

$('#direction-form').submit(function () {
  // clear previous
  clearRenderObjects();
  ...
  var directionsRenderer = new google.maps.DirectionsRenderer();
  directionsRenderer.setMap(map);
  // add to the array
  renderObjects.push(directionsRenderer);
  ...
});
查看更多
做自己的国王
3楼-- · 2020-05-06 12:43

Use the same DirectionsRenderer-instance for all requests(currently you create a new instance on each request)

查看更多
登录 后发表回答