Search code examples
geojsonmapbox-gl-js

Mapbox GL JS - Analysis of Filtered Markers


I'm new to Mapbox GL JS, and am loving it! A couple of things I've run into when filtering markers on a GeoJson source that I'm wondering if someone can help me out with...here's a sample of my filter logic:

    function applyFilters() {
        var filters = ["all", ["==", "$type", "Point"]];

        if (document.getElementById('filter1checkbox').checked)
            filters.push(['==', 'property1', true]);
        if (document.getElementById('filter2checkbox').checked)
            filters.push(['==', 'property2', true]);

        map.setFilter('markers', filters);
        var llb = new mapboxgl.LngLatBounds(geojsonExtent(markers));
        map.fitBounds(llb);
        map.setCenter(llb.getCenter());
    }

And here's my questions:

  1. Once my filter is applied, is there a way to get a count of markers that matched the filter (Your search returned {X} items)?
  2. When I use geojsonExtent to get the bounds of the marker collection, it doesn't seem to be taking the filter into account. Is there a way to get at the data behind the filter to pass into geojsonExtent?

Any advice on where to go for these items?


Solution

  • Once my filter is applied, is there a way to get a count of markers that matched the filter (Your search returned {X} items)?

    You can get the number of filtered markers currently visible in the viewport by running

    map.queryRenderedFeatures({layers: ['markers']).length
    

    There is no way to get the total number of filtered markers across the whole map.

    When I use geojsonExtent to get the bounds of the marker collection, it doesn't seem to be taking the filter into account. Is there a way to get at the data behind the filter to pass into geojsonExtent?

    You can use queryRenderedFeatures for this too! (Note: this code is untested)

    geojsonExtent({
      type: 'FeatureCollection',
      features: map.queryRenderedFeatures({layers: ['markers']).length
    });