以下是我用于从给定点生成路线的功能。我有几个地方,用户可以从...请求方向...如果用户第二次请求方向,那么第一条路线仍然显示在地图上,显然这看起来不太好。我该如何删除它?
base.getRoute = function(start, la, lo) {
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(base.map);
directionsDisplay.setPanel(document.getElementById("drivingDirectionsPanel"));
start+=",uk";
var end = new google.maps.LatLng(la, lo);
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response,status) {
if(status == google.maps.DirectionsStatus.OK) {
$('#drivingDirectionsPanel').html('');
directionsDisplay.setDirections(response);
$('html, body').animate({
scrollTop: $('#drivingDirectionsPanel').offset().top
}, 1500);
} else {
alert("There was a problem finding directions");
}
});
};
我尝试过添加
directionsDisplay.setMap(null);
但这不起作用。
任何想法的家伙?感谢
答案 0 :(得分:1)
使路线显示“类”或全局变量,以便在渲染方向时撤消面板。
答案 1 :(得分:0)
以下是我的表现:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.extend(map,{
pv: {
markerArray: [],
areaCircle: null,
userLocation: {
latitude: 38.68551,
longitude: -98.789062
},
removeAllMarkers: function(){
for (var i = 0; i < this.markerArray.length; i++) {
if (this.markerArray[i].directions) this.markerArray[i].directions.setMap(null);
this.markerArray[i].setMap(null);
}
},
removeAllDirections: function(){
for (var i = 0; i < this.markerArray.length; i++) {
if (this.markerArray[i].directions) this.markerArray[i].directions.setMap(null);
}
},
geocoder: new google.maps.Geocoder(),
directions: new google.maps.DirectionsService(),
directionPanel: document.getElementById('directions'),
center: null
}
});
现在,无论何时添加标记,我都会在markerArray中添加对它的引用,然后当我想删除所有方向或所有标记时,我只需调用map.pv.removeAllDirections()
或map.pv.removeAllMarkers()
答案 2 :(得分:0)
directionsDisplay.setMap(null);
map.setZoom(8);
map.setCenter();
答案 3 :(得分:0)
我使用上面建议的解决方案组合工作。因此,“directionsDisplay”需要是全局的,然后在创建directionsDisplay之前需要调用directionsDisplay.setMap(null),它将从地图中清除以前的路径。
以下是代码:
if(directionsDisplay != undefined)
directionsDisplay.setMap(null);
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({preserveViewport:true});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvDirResults'));
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
$('#<%= lblGetDirError.ClientID %>').hide();
$('#dvDirResults').html("");
directionsDisplay.setDirections(response);
map.panToBounds(response.routes[0].bounds);
map.setCenter(response.routes[0].bounds.getCenter());
//map.fitBounds(response.routes[0].bounds);
if(map.getZoom() < 10) map.setZoom(10);
}
else
$('#<%= lblGetDirError.ClientID %>').show();
});