谷歌地图v3 directionsRenderer.setMap(null)不工作,以清除以前的方向



我正试图从谷歌地图上清除以前的方向。但是当您进行另一次搜索时,前一次搜索的折线和标记仍然显示。我尝试过使用directionsRenderer.setMap(null),但它没有任何区别。知道我哪里做错了吗?

(function () {    
    Maps.Directions = function(googleMap, data, options) {
        var directionsService = new google.maps.DirectionsService(),
            directionsRenderer = new google.maps.DirectionsRenderer();
        function getDirections() {
            directionsService.route(data.request, function(response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    directionsRenderer.setDirections(response);
                }
            });
        }
        directionsRenderer.setMap(null);
        directionsRenderer.setMap(googleMap);
        getDirections();
    };
})();

这是因为您在每次调用该函数时都初始化了一个新的directionsRenderer

让directionsRenderer全局化一点。先setMap(null),再初始化,再setMap(googleMap)

:

(function () {   
    var directionsRenderer;
    Maps.Directions = function(googleMap, data, options) {
        if(directionsRenderer){
            directionsRenderer.setMap(null);
        }
        var directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer();
        function getDirections() {
            directionsService.route(data.request, function(response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    directionsRenderer.setDirections(response);
                }
            });
        }
        directionsRenderer.setMap(googleMap);
        getDirections();
    };
})();

最新更新