0
votes

I'm trying to add some basic filters to a Mapbox map. The map is pulling data from a geojson data file. The fields in my data that I would like to filter are # of bedrooms and price range. The bedrooms data is literally just 0-5 and the price range is basic number format: 1000, 2500, 4000. Ideally just a simple radio button for the bedrooms and a price range slider. So far I tried the Mapbox checkbox example here: https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/ but this does not work with geojson data url source. I also tried this example for the radio buttons: https://docs.mapbox.com/help/tutorials/show-changes-over-time/. This references a date range though which doesn't work for my use case. Are there any other examples I could reference? I briefly looked into the setfilter function with no luck. I'm really struggling with this issue so any tips or ideas would be helpful. Thanks in advance!

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Test</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user- 
scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox- 
gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css' 
rel='stylesheet' />
<style>
body { margin:0; padding:0; height:500px;}
#map { position:absolute; top:0; bottom:0; width:91%; height:500px;}
img {
height: 100px;
width: 120px;
}
.mapboxgl-ctrl-compass {
display: none !important;
}
</style>
</head>
<body>

<div id='map'></div>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl- 
geocoder/v2.3.0/mapbox-gl-geocoder.min.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl- 
js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.css' type='text/css' 
/>
<script>
mapboxgl.accessToken = 'mycode12345';
var address = localStorage.getItem('address'); //local storage item from 
previous page
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/dark-v9',
center: address, //How would I pass it to the map center?
zoom: 3
});

map.on('load', function() {
map.addSource("Properties", {
type: "geojson",
data: "mydataurl",
cluster: true,
clusterMaxZoom: 14, 
clusterRadius: 50
});

map.addLayer({
id: "clusters",
type: "circle",
source: "Properties",
filter: ["has", "point_count"],
paint: {
"circle-color": [
"step",
["get", "point_count"],
"#ffffff",
100,
"#ffffff",
750,
"#ffffff"
],
"circle-radius": [
"step",
["get", "point_count"],
20,
100,
30,
750,
40
]
}
});

map.addLayer({
id: "cluster-count",
type: "symbol",
source: "Properties",
filter: ["has", "point_count"],
layout: {
"text-field": "{point_count_abbreviated}",
"text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
"text-size": 12
}
});

map.addLayer({
id: "unclustered-point",
type: "circle",
source: "Properties",
filter: ["!", ["has", "point_count"]],
paint: {
"circle-color": "#ffffff",
"circle-radius": 8,
"circle-stroke-width": 1,
"circle-stroke-color": "#fff"
}
});

map.on('click', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['unclustered-point'] // replace this with the name of the layer
});

if (!features.length) {
return;
}

var feature = features[0];

var popup = new mapboxgl.Popup({ offset: [0, -15] })
.setLngLat(feature.geometry.coordinates)
.setHTML('myhtml')
.setLngLat(feature.geometry.coordinates)
.addTo(map);
});
});

map.on('mouseenter', 'clusters', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'clusters', function () {
map.getCanvas().style.cursor = '';
});
map.addControl(new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
placeholder: "Location",
animate: false,
zoom: 7.2
}), 'top-left');
map.addControl(new mapboxgl.NavigationControl(), 'bottom-right');
</script>

</body>
</html>
1

1 Answers

0
votes

I am currently working on a project where I have geoJSON that contains polygons, and a database of properties ( including lat/long positions for markers ). My solution to what I think you are doing goes as follows:

https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/

When I use the tutorial to turn layers ( geoJSON layers ) on and off I include a new function which does a seperate filtering of data and results

    if (visibility === 'visible') {
        map.setLayoutProperty(clickedLayer, 'visibility', 'none');
        this.className = '';
    } else {
        this.className = 'active';
        map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
        if ( clickedLayer == 'Corn' ){
        FilterCorn();
    }if ( clickedLayer == 'MultiPoly' ){
        FilterMulti();
    }
    }

Example if I turn on my layer which contains polygons showing corn data, I call this function which can determine if points ( markers ) exist within the layers features ( 1 feature = 1 polygon ).

 function FilterCorn() { 

    $(function() {
      var cluster = [];
      var features = [];
      var point = turf.point([-76.161496, 45.4734536]); 
      var url = '/geoJSON/Corn.json';

      $.getJSON(url, function(data)
      {
        features = data.features;

        for (var i = 0, len = features.length; i < len; i++)
        {
          // Get coordinates
          var is_inside = turf.inside(point, features[i]);
          console.log(is_inside);

          if (is_inside) {
            console.log('Found it inside');
          }
        }

        console.log(cluster);
      });
    });

If you can provide a fiddle I will be happy to edit it to do what you want.