Angular删除Google地图标记

时间:2018-05-03 10:29:23

标签: angular typescript ionic-framework google-maps-markers

我试图在按钮点击时从地图中删除所有标记;

gmarkers = []; //define empty array for all markers

添加标记,显示地图:

addMarkersToMap(markers) { 
    for(let marker of markers) {
    var  position = new google.maps.LatLng(marker.latitude,   marker.longitude);
    var myMarker = new google.maps.Marker({
       position: position,
       title: marker.name
     });
     myMarker(this.map);
     this.gmarkers.push(marker); //push all markers to gmarkers array
   }
}

删除标记:

removeMarkers(){
  if (this.gmarkers) {
      for (let i in this.gmarkers) {
        this.gmarkers[i].setMap(null);
      }

      this.gmarkers = [];
   }
}

还尝试使用此方法删除:

removeMarkers(){
    for(var i=0; i<this.gmarkers.length; i++){
      this.gmarkers[i].setMap(null);
    }
   this.gmarkers = [];
}

我收到了错误:

  

this.gmarkers [i] .setMap不是函数

1 个答案:

答案 0 :(得分:1)

试试这个:改为使用foreach

removeMarkers(){
    this.gmarkers.foreach((marker)=>{
        marker.setMap(null);
        marker = null;
    })
   this.gmarkers = [];
}

在您的addMarkersToMap()方法中,您正在推送marker变量,而我需要在myMarker内推送gmarkers

addMarkersToMap(markers) { 
    for(let marker of markers) {
    var  position = new google.maps.LatLng(marker.latitude,   marker.longitude);
    var myMarker = new google.maps.Marker({
       position: position,
       title: marker.name
     });
     myMarker(this.map);
     //replace marker with myMarker
     this.gmarkers.push(myMarker); //push all markers to gmarkers array
   }
}