Search code examples
javascriptjqueryclassleafletshow-hide

Leaflet: Hide/Show Markers that are being inserted dynamically into the map


i'm inserting the map points like this:

function getPoints() {
  $.getJSON("get_users.php", function (data) {
    for (var i = 0; i < data.length; i++) {
      var location = new L.LatLng(data[i].lat, data[i].lng);
      var name = data[i].name;
      var website = data[i].website;
      var teste = "teste" + website;

      var marker = new L.Marker(location, {
        icon: tree1
      });
      marker.bindPopup("<a onclick='info()' style='font-size:18px; font-style: italic; font-family:courier; cursor: pointer;'>" + name + "</a><p>" + city + "</p><p id='inf' style='display:none;'>" + website + "</p><p style='font-size:10px;'>" + location + "</p>", {maxWidth: '400'});
      users.addLayer(marker);
    }
  }).complete(function() {
    if (firstLoad == true) {
      map.fitBounds(users.getBounds());
      firstLoad = false;
    };
  });
}

And i wanted the users to be able to only see the markers, for example with the class "foo", using javascript to hide the points that don't have that class.

My problem is that i have not been able to assign a class to the marker.. i have tried:

Using JQuery: $(marker._icon).addClass(foo) , $(marker).addClass('foo')

DomUtil: DomUtil.addClass(marker, 'foo') , marker = L.DomUtil.addClass(marker, 'foo')

Am i doing something wrong declaring the class? please correct me!


Solution

  • You can make an array of LayerGroups with your markers and then, with a sub array, you can put only the markers you want to show, and remove and add whenever you want it