Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

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

I want to clear a marker on Google Maps.

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

But I don't know, which is right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Map object, you wouldn't be able to reshow the marker.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...