TruMan1
TruMan1

Reputation: 36158

How to toggle multiple overlays in Google Maps?

I have a click event that grabs coordinates remotely, lays them on a map, and connects them with a polyline. I have other click events that do the same, but want to keep them as a separate layer so that the user can toggle to view each of the clicks they have done. Does anyone know of a good way to group them separately to do this or another approach?

Here is my code so far:

drawPoints: function (points, color) {
    $.each(points, function (key, val) {
        var location = new google.maps.LatLng(val.Latitude, val.Longitude);
        MyTest.addMarker(location, val.Name, val.Description);
        MyTest.coordinates.push(location);
    });

    this.path = new google.maps.Polyline({
        path: MyATest.coordinates,
        strokeColor: color,
        strokeOpacity: 1.0,
        strokeWeight: 2
    });

    this.path.setMap(this.googlemap);
},

addMarker: function (location, title, html) {
    var marker = new google.maps.Marker({
        position: location,
        map: this.googlemap,
        title: title,
        html: html
    });

    this.markers.push(marker);
},

// Removes the overlays from the map, but keeps them in the array
clearOverlays: function () {
    if (this.markers) {
        for (i in this.markers) {
            this.markers[i].setMap(null);
        }
    }
},

// Shows any overlays currently in the array
showOverlays: function () {
    if (this.markers) {
        for (i in this.markers) {
            this.markers[i].setMap(map);
        }
    }
},

Upvotes: 1

Views: 699

Answers (1)

Adam Jenkins
Adam Jenkins

Reputation: 55792

You've got them kept in this.markers - which is a great start. Now all you need to do is define a click listener function for each marker:

for(i in this.markers) {
    google.maps.addListener(this.markers[i], function() {
        this.markers[i].clicked = true; });
}

Then, whenever a user wants to toggle only the markers they've clicked on, loop through your markers (like you are doing) and setMap to null on all where this.markers[i].clicked === undefined.

Upvotes: 1

Related Questions