Harry
Harry

Reputation: 1150

How do I toggle markers?

My code to make 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'm trying to be able to toggle the markers with a checkbox like so:

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

But only the last marker in the array is shown, how do I make all of them appear?

Thanks.

Upvotes: 4

Views: 8302

Answers (1)

Tina CG Hoehr
Tina CG Hoehr

Reputation: 6779

Well, I see posMarker being used as a temporary variable that places a Google Maps marker, and as the for loop progresses, the posMarker reference "updates" to the latest marker placed. That's why only the last marker is being shown.

You need to keep track of all references to Google Maps markers being placed, including those that have been "consumed". My approach uses an object, much like your markers object but holding references to Google Maps markers. You could also use a plain indexed array (posMarkers[]). It's up to you.

See the Demo, note the LatLngs have been modified for simplicity (looks like you have a custom coordinate system).

Also, I didn't make this change, but I just noticed that it may make more sense to call marker in markers, city in markers because the way your object is written. It would be more readable, but won't affect the execution.

Finally, semicolons at the end of for loops blocks are unneeded, and be careful with the trailing comma after the Paris object (I'm guessing you just erased the rest of the list). In this case it didn't matter, but other times these trailing commas can be a source of hard-to-find bugs.

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);
            }
        }
    });
}

Upvotes: 6

Related Questions