我想在搜索后删除谷歌地图方向标记而不重新加载页面。我做了一个例子,但它不起作用:
//First of all testing if there is already a direction on the map
if(directionsService != null)
{
directionsService.setMap(null);
directionsService = null;
}
//Then display the new one
var origin = $('#de').val();
var destination = $('#en').val();
var request = {
origin : origin,
destination : destination,
travelMode : google.maps.DirectionsTravelMode.DRIVING
}
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
direction.setDirections(response);
showSteps(response);
}
});
所有这些代码都位于由点击事件调用的函数上
<button id="envoyer" id=="env" onclick="javascript:c()">Send</button>
所以任何人有一个想法谢谢!
更新
function showSteps(directionResult) {
var markerArray = [];
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
最佳答案
清除行程时,使用 directionsService.setMap(null);
您必须单独删除不直接连接到方向服务的 map 标记。
您已经将它们存储在 showSteps
函数内的 markerArray
中,因此您需要将此变量移出函数到外部作用域,或者让函数返回它以便能够访问它。
通过这样做,您可以简单地遍历markerArray并对每个存储的Marker调用.setMap(null)
,从而将它们从 map 中删除。
var markerArray = [];
function showSteps(directionResult){
// your code
}
//function to remove MapMarkers
function removeMapMarkers(){
for(var i=0; i<markerArray.length; i+=1){
markerArray[i].setMap(null)
}
markerArray = [];
}
关于javascript - 如何删除谷歌地图API中的方向标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25502549/