simon
simon

Reputation: 6117

Google Maps V3: Check if marker is present on map?

In Google Maps V3, is there a way to check whether a marker is actually present on the map?

I have markers that vanish when clicked. I'd like some logic to check the present visibility of the marker.

For example:

var start_marker = null;
start_marker = new google.maps.Marker({ position: location, map: map, clickable: true });
google.maps.event.addListener(start_marker, 'click', function(event) {
  start_marker.setMap(null);
}); 
// ... Later in code: check whether marker is currently visible. 
console.log('Type of start_marker is now: ' + typeof(start_marker));

I was hoping this would give me a null type when the marker isn't visible, but in fact it's still an Object.

So, how else can I check whether this particular marker is visible on the map?

Thanks!

Upvotes: 31

Views: 40751

Answers (5)

eyecatchUp
eyecatchUp

Reputation: 10560

This one-liner will return true if the marker's position is contained under the current map boundary, and return false if not.

map.getBounds().contains(marker.getPosition())

Upvotes: 72

cristy
cristy

Reputation: 317

If you wish to just to hide/show the marker you could use the setVisible method of of the marker like:

 start_marker.setVisible(false);//to hide
 start_marker.setVisible(true);//to show

because setMap(null) does not hide the marker but removes the marker from the map.

You could then use getVisible() to get the visibility of the marker like:

console.log('Type of start_marker is now: ' + start_marker.getVisible());

You could read them here: https://developers.google.com/maps/documentation/javascript/overlays#Markers https://developers.google.com/maps/documentation/javascript/overlays

Upvotes: 10

Argiropoulos Stavros
Argiropoulos Stavros

Reputation: 9533

I think you have to change your logic.Why not store your markers in an array and remove them completely from this array when they are clicked.So the remaining markers are the visible ones.

Cheers

Upvotes: 0

no.good.at.coding
no.good.at.coding

Reputation: 20371

Marker#getVisible() ?

Upvotes: 5

Jasoon
Jasoon

Reputation: 432

start_marker.getMap()

Would return null if you'd previously used start_marker.setMap(null); as in your example.

That said, why not use setVisible and getVisible if you just want to hide and show markers?

Upvotes: 11

Related Questions