Filtering through Mapbox points with Mapbox GL JS by properties

519 views Asked by At

I currently have Mapbox running on my site, data points and popups are function while using a dataset uploaded to Mapbox Studio. For the life of me, I cannot filter the points by properties in Javascript (within my html file script tag). I tried setFilter() examples and nothing seems to work.

By the way, I censored our access token and styles url. All of that is working on my end.

        mapboxgl.accessToken = 'pk........';
        const map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/........',
            center: [-111.9671707, 33.30527115],
            zoom: 15
        });

        map.on('click', (event) => {
            const features = map.queryRenderedFeatures(event.point, {
                layers: ['crime-data-complete (1)'] 
            });
            if (!features.length) {
                return;
            }
            const feature = features[0];
            
            const popup = new mapboxgl.Popup({ offset: [0, -15] })
                .setLngLat(feature.geometry.coordinates)
                .setHTML(
                    `<h2 style="text-transform: capitalize;">${feature.properties.Crime}</h2><p><strong>Date: </strong>${feature.properties.Date}</p><p><strong>Address: </strong>${feature.properties.Address}</p><p><strong>City: </strong>${feature.properties.City}</p><p><strong>State: </strong>${feature.properties.State}</p>`
            )
            .addTo(map);
        });

        map.setFilter('crime-data-complete (1)', ['all', ['==', 'Crime', 'Theft']]);
1

There are 1 answers

0
AgedPeanuts On BEST ANSWER

If you are using the ['all', ...] then you should include a get for the properties.

In your case that would be:

map.setFilter('crime-data-complete (1)', ['all', ['==', ['get', 'Crime'], 'Theft']]);

If you're using one filter only, you can drop the ['all', ...] and use this instead:

map.setFilter('crime-data-complete (1)', ['==', 'Crime', 'Theft']);