删除以前的路线路线谷歌地图

时间:2015-06-01 08:04:28

标签: javascript google-maps google-maps-api-3

  

嗨,我正在尝试从信息窗口规划路线,但我无法做到   删除先前设置的路线。我尝试了setMap(null)但它没有   工作。我正在使用一个事件监听器的回调,因为我需要传递从api调用返回的参数。一种选择是在每个事件上使用新的google.maps.map,例如(link)在标记上,但在页面加载时已经放置了我的标记。

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


    }
}

1 个答案:

答案 0 :(得分:6)

仅定义directionsDisplay一次(在click - 处理程序之外)