Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 938
zjm1126 Avatar asked Sep 05 '10 20:09

zjm1126


People also ask

What is the marker on Google Maps called?

The Google Maps pin is the inverted-drop-shaped icon that marks locations in Google Maps. The pin is protected under a U.S. design patent as "teardrop-shaped marker icon including a shadow". Google has used the pin in various graphics, games, and promotional materials.

How do you customize a marker in maps?

For adding a custom marker to Google Maps navigate to the app > res > drawable > Right-Click on it > New > Vector Assets and select the icon which we have to show on your Map. You can change the color according to our requirements. After creating this icon now we will move towards adding this marker to our Map.


2 Answers

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.

like image 117
Daniel Vassallo Avatar answered Oct 02 '22 13:10

Daniel Vassallo


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.

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

like image 24
Phil Glau Avatar answered Oct 02 '22 14:10

Phil Glau