Javascript 如何在google map API中删除方向标记

Javascript 如何在google map API中删除方向标记,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我想删除谷歌地图的方向标记后,没有重新加载页面搜索。我举了一个例子,但它不起作用: //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

我想删除谷歌地图的方向标记后,没有重新加载页面搜索。我举了一个例子,但它不起作用:

//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;
  }
}
函数显示步骤(方向结果){
var-markerary=[];
var myRoute=directionResult.routes[0]。legs[0];
对于(var i=0;i
清除行程时,使用
directionsService.setMap(空)你将不得不移除地图标记,它们也没有直接连接到方向服务

您已经将它们存储在
showSteps
-函数内部的
markerary
中,因此您需要将此变量从函数中移出到外部作用域中,或者让函数返回以访问它

通过这样做,您可以简单地在markerArray上循环,并对每个存储的标记调用
.setMap(null)
,从而将它们从映射中删除

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 = [];

}
var-markerArray=[];
函数showSteps(directionResult){
//你的代码
}
//函数删除地图标记
函数removeMapMarkers(){

对于(var i=0;ii,如果我记得正确,
directionService.setMap(null);
至少应该使方向不可见,
directionService=null
将同时删除它。你说的“它不工作”是什么意思?它会删除行程,但不会删除标记。那么,显示你的
showSteps
-函数,我们猜不出你在其中做了什么。我已经在文本中添加了它!谢谢,它起作用了,我的错是我将标记数组声明在函数内部而不是外部