Update Features on bounds changed
See original GitHub issueI wish to update the features of a layer each time the map changes bounds.
I have looked at @alex3165’s talk, and it’ similar to the effect at 14:56. However, one crucial difference: if I understood correctly in the video all the features are loaded at init, and the left pane is only filtering based on bounds.
What I wish to achieve is: since I have a lot of features, I don’t want to load them all, but only load the ones that are visible, i.e. in the bounds of the map. And every time I drag/zoom/rotate the map, the list of features updates.
Here’s how I would do it:
// In the render method
<MyMap
listings={this.props.listings}
boundsChanged={map => {
console.log(map.getBounds()); // This works
this.getListings(map.getBounds());
}}
/>
Where this.getListings
is an API call which retrieves listings in the bounds and updates this.props.listings
.
And here is my implementation of <MyMap />
:
// In the render method
<Map
style="mapbox://styles/mapbox/streets-v9" // eslint-disable-line
containerStyle={{ width: '100vw', height: '100vh' }}
onDrag={boundsChanged}
onRotate={boundsChanged}
>
<Layer
type="symbol"
id="listings"
layout={{ 'icon-image': 'marker-15' }}
>
{listings.map((listing) => (
<Feature coordinates={[listing.longitude, listing.latitude]} key={listing._id} />
))}
</Layer>
</Map>
However, what happens is that when I drag, the map re-renders, and go back to the initial bounds (around London).
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
The center will change only if you break the reference of the array of your center prop. The solution if you want to leave mapbox handling the center is to keep your center in the state and do not break the reference between re-render. If you want to take over the control of the center then you just break the reference by creating a new array, even if the value are the same it will update the center to the value you pass as a prop (zoom work the same way).
It is not natural at first and not very well documented (I will work on it) but I think it is better than keeping the viewport in sync with mapbox’s viewport which would trigger lot of re-rendering of the map component like react-map-gl is doing.
@Wykks Yes my bad, that did the trick. I defined Map inside a function component.
And thank you all for all the comments!