In Google Maps v3, how do marker.setVisible(false) and marker.setMap(null) differ from each other?

Upon page load, an array will be populated with 6 markers indicating regions on Google maps. However, if the user chooses to zoom in, these markers will be replaced with a varying number of markers indicating cities. The user seeks to modify the markers based on the zoom level in Google Maps.

Question:

My intention is to remove a marker from
Google maps
.

Can you clarify how

marker.setVisible(false)

differs from

marker.setMap(null)

?

But I don’t know, which is right?


Solution 1:

Although there is a lack of clear documentation about the distinction between the two methods, it is important to consider the following points:

  • Using <code>
    setMap(null)
    </code> will cause the marker to no longer reference <code>
    Map
    </code>. Thus, it is essential to keep a reference to the <code>
    Map
    </code> object to be able to <a class=”text-blue-600″ href=”https://in4any.com/python-matplotlib-how-to-reshow-a-figure-of-subplots-after-having-called-plt-show” title=”Python-matplotlib: how to reshow a figure of subplots after having called plt.show()?”>reshow</a> the marker.

  • Moreover, the <code>
    setMap()
    </code> technique does not activate the <code>
    visible_changed
    </code> occurrence, whereas the <code>
    setVisible()
    </code> approach does so (in case the visibility is genuinely switched).

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

It seems that the

setVisible(false)

approach is more suitable for displaying the marker again on the map, while the

setMap(null)

method is better suited when we do not plan on displaying it again.


Solution 2:


One important difference between

setMap(NULL)

and

setVisible(false)

is that the former releases the associated resources of the marker, while the latter only hides the marker without deallocating the resources.

When you have a large number of markers, it can lead to performance and memory problems.

Frequently Asked Questions