Search code examples
javascriptleafletmappinggeojson

Toggle GeoJSON layer in leaflet sidebar


How can I toggle the GeoJSON layers in my leaflet map as I would the L.marker layers?

https://jsfiddle.net/mawr35vj/

Please pardon me if this is a simple question, I'm still new to leaflet and have spent all day on this.

Here is the GeoJSON I would like toggled in the sidebar.

fetch('https://data.cityofnewyork.us/resource/ek5y-zcyf.geojson?$where=latitude is not null')
  .then(function (response) {
    // Read data as JSON
    return response.json();
  })
  .then(function (data2) {
    // Create the Leaflet layer for the data 
    var complaintLayer = L.geoJson(data2, {

      // We make the points circles instead of markers so we can style them
      pointToLayer: function (geoJsonPoint, latlng) {
        return L.circleMarker(latlng);
      },

      // Then we can style them as we would other features
      style: function (geoJsonFeature) {
        return {
          fillColor: '#0000ff',
          radius: 6,
          fillOpacity: 0.7,
          stroke: false
        };
      }
    });
  });


-I tried assigning it a "var"
-I tried adding "complaintLayer" in the overlays as I did with the L.marker
-And many other various things that I can't remember but is obviously not working...

Update:

I'm trying to load the GeoJSON and assign it a variable, but having difficulty. I'm looking at this and related threads: How can I assign the contents of a geojson file to a variable in Javascript?

I got it to work if I just copy and paste the GeoJSON into the script, but having difficulty if I want to load it from a local file or API.


Solution

  • You can put complaintLayer in an array for a marker control, but the variable must be in the right scope - from the code you've posted it looks like it's local to the function it's populated in, so it won't be visible outside.