How to switch markers?

My code for creating markers:

for (var marker in markers) { var posMarker = new google.maps.Marker({ position: new google.maps.LatLng(markers[marker].lat, markers[marker].lng), map: map, visible: markers[marker].visible }); }; 

My markers object:

 var markers = { "London": {"lat": -83.68088192646843, "lng": -125.270751953125, "type": "town", "visible": false}, "Paris": {"lat": -58.1548020417031, "lng": -21.318115234375, "type": "town", "visible": false}, }; 

I am trying to toggle markers using a checkbox:

 $('#toggle').change(function() { for (var marker in markers) { posMarker.setVisible(true); }; }); 

Only the last marker in the array is shown, how can I do all of them?

Thanks.

+4
source share
1 answer

Well, I see that posMarker used as a temporary variable that places the Google Maps marker, and as the for loop progresses, the posMarker link posMarker β€œupdated” to the last marker placed. This is why only the last marker is displayed.

You need to track all links to Google Maps markers, including those that have been "consumed." My approach uses an object similar to your markers object, but containing links to Google Maps markers. You can also use a simple indexed array (posMarkers []). It depends on you.

See Demo , note that LatLngs have been changed for simplicity (it looks like you have a custom coordinate system).

Also, I did not make this change, but I just noticed that it makes sense to call marker in markers , city in markers , because there is a way to write your object. This would be more readable, but would not affect execution.

Finally, semicolons at the end are not required for cycle loops, and be careful with the trailing comma after the Paris object (I think you just erased the rest of the list). In this case, it did not matter, but in other cases, these trailing commas can be a source of hard-to-reach errors.

  function initialize() { map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); var markers = { "London": {"lat": 0, "lng": 0, "type": "town", "visible": false}, "Paris": {"lat": 10, "lng": 10, "type": "town", "visible": false} }; var posMarkers = {}; for (var marker in markers) { posMarkers[marker] = new google.maps.Marker({ position: new google.maps.LatLng(markers[marker].lat, markers[marker].lng), map: map, visible: markers[marker].visible }); } $('#toggle').change(function() { for (var marker in markers) { if(posMarkers[marker].getVisible()) { posMarkers[marker].setVisible(false); } else { posMarkers[marker].setVisible(true); } } }); } 
+6
source

All Articles