Andy Harvey
Andy Harvey

Reputation: 12653

How to get the results of a filtered Mapbox layer?

I am trying to update an old Mapbox.js map to Mapbox GL. I am generating the map from geojson (and using coffescript).

map.addSource 'my_datasource',
  'type': 'geojson'
  'data': my_geojson

map.addLayer
  'id': 'my_layer'
  'type': 'symbol'
  'source': 'my_datasource'

I am filtering the layer based on a user input that returns value

map.setFilter('my_layer', ["==", 'my_attribute', value ])

So far, so good. But now I want to zoom and reposition the map to fit the bounds of the filtered symbols.

I thought I would be able to do something like this

bounds = new (mapboxgl.LngLatBounds)
map.queryRenderedFeatures(layers: [ 'my_layer' ]).forEach (feature) ->
  bounds.extend feature.geometry.coordinates
  return
map.fitBounds bounds

But queryRenderedFeatures appears to be returning all (i.e., un-filtered) symbols.

After much reading around, my understanding is that queryRenderedFeatures should return the filtered symbols that are visible in the viewport (i.e., would be suitable for zooming in but not zooming out).

Is this correct? And if so, why is my function above returning unfiltered symbols? Appreciate any advice to help my transition to MapboxGL!

Upvotes: 2

Views: 3967

Answers (2)

Asrar
Asrar

Reputation: 495

Try this post, I have added the code which will let you have the features using queryRenderedFeatures() or even using querySourceFeatures(): https://stackoverflow.com/a/66308173/9185662

Upvotes: 1

Steve Bennett
Steve Bennett

Reputation: 126205

It's a bit unclear to me from the documentation whether filters in the layer should be applied, but in any case, there is an explicit filter parameter you can, pass, so:

map.queryRenderedFeatures(layers: [ 'my_layer' ],  filter:["==", 'my_attribute', value ]).forEach (feature) ->
  bounds.extend feature.geometry.coordinates

But I suspect you really want querySourceFeatures, because you don't want to be constrained by what's currently within the viewport:

map.querySourceFeatures(my_source,  filter:["==", 'my_attribute', value ]).forEach (feature) ->
  bounds.extend feature.geometry.coordinates

or, in native ES2015:

map.querySourceFeatures(my_source,  { filter:['==', 'my_attribute', value ]} )
   .forEach (feature => bounds.extend(feature.geometry.coordinates))

Upvotes: 2

Related Questions