javascript - 如何删除谷歌地图API中的方向标记

标签 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 = $('#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/

相关文章:

php - jQuery 函数调用 ajax 不起作用/返回任何内容

swift - 如何在 swift 3.0 中从 google api 获取时间值

java - 谷歌地图 Android API v2

php - 非英语地址的 Google map API 问题 (PHP/CURL)

javascript - 删除 Google Maps API V3 中的平移控件

google-maps - 使用具有许可的 Google Maps API for Business

javascript - 使用 jquery 从类中获取 css 属性

javascript - 在php中点击动态按钮调用参数化函数

javascript - 模拟 Javascript 面向对象编程 Stoyan Stefanov 书中的字符串 split()

javascript - Google Maps Tile Overlays - 在调用图 block 时避免 404 错误?