Javascript Google Maps v3 中的“marker.setVisible(false)”和“marker.setMap(null)”有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3647711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:34:48  来源:igfitidea点击:

What is the difference between "marker.setVisible(false)" and "marker.setMap(null)" in Google Maps v3?

javascriptgoogle-mapsgoogle-maps-api-3google-maps-markersclear

提问by zjm1126

I want to clear a marker on Google Maps.

我想清除 Google 地图上的标记。

What is the difference between marker.setVisible(false)and marker.setMap(null)?

marker.setVisible(false)和 和有marker.setMap(null)什么区别?

But I don't know, which is right?

但我不知道,哪个是对的?

回答by Daniel Vassallo

The difference between the two methods does not seem to be clearly documented. However, note the following:

这两种方法之间的区别似乎没有明确记录。但是,请注意以下几点:

  • When you use setMap(null), your marker will lose the reference to the Map. If you do not keep a reference to the Mapobject, you wouldn't be able to reshow the marker.

  • In addition, the setMap()method will not trigger the visible_changedevent, while the setVisible()method does (if the visibility is actually toggled).

  • 当您使用 时setMap(null),您的标记将丢失对 的引用Map。如果您不保留对Map对象的引用,您将无法重新显示标记。

  • 此外,该setMap()方法不会触发visible_changed事件,而该方法会触发setVisible()(如果可见性实际上已切换)。

Example:

例子:

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 4,
  center: new google.maps.LatLng(-25.363, 131.044),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(-25.363, 131.044), 
  map: map
}); 

google.maps.event.addListener(marker, 'visible_changed', function() {
  console.log('visible_changed triggered');
});

marker.setVisible(false); // visible_changed triggered
marker.setVisible(true);  // visible_changed triggered
marker.setMap(null);      // visible_changed not triggered
marker.setMap(map);       // visible_changed not triggered

I guess we should be using the setVisible(false)method when we intend to reshow the marker again on the map, and the setMap(null)when we will not be showing it again.

setVisible(false)想当我们打算在地图上再次重新显示标记时,我们应该使用该方法,而setMap(null)当我们不会再次显示它时。

回答by Phil Glau

Another key distinction is that setMap(NULL)releases the resources associated with the marker whereas setVisible(false)just makes the marker invisible, but the resources associated with the marker are still allocated.

另一个关键区别是setMap(NULL)释放与标记关联的资源,而setVisible(false)只是使标记不可见,但与标记关联的资源仍然被分配。

If you're dealing with 100s or 1000s of markers, this can become a significant performance and memory issue.

如果您正在处理 100 或 1000 个标记,这可能会成为一个重要的性能和内存问题。