I am working with mapbox in a react application. Accordiong to mapbox docs you can target a layer on map click with code like this. map.on('click', 'poi-label', (e) => {// do lots of stuff in the map })
Currently, I have something like this in my componentDidMount
function because it works, when I click on each map marker I can see each instance and relevant info for that marker. I want to move this block into its own onClick
but I am wondering how do you pass a layer selector such as poi-label
to an onClick and how can I maintain each instance of each marker on click when I break it out from the current click block?
I was thinking something like this but all instances of the markers are triggered on click which is not what I want.
handleClick(layer, e) {
const map = this.state.map
let features = map.queryRenderedFeatures(e.point, {
layers: ['poi-label']
});
let feature = features[0];
const popup = new mapboxGl.Marker(this.popupContainer, { offset: [0, -75] })
.setLngLat(feature.geometry.coordinates)
.addTo(map);
this.popupElement = popup._element
this.popupName = feature.properties.name
let favoritePOI = this.state.favoritePOI
this.setState({ showPopup: true, popupInstance: this.popupElement, currentName: this.popupName });
map.flyTo({ center: e.lngLat});
this.setPopUp(features, this.addFavorite, this.closeMarker, favoritePOI)
}
Where the onClick is attached in render
render() {
const layer = 'poi-label'
return <div ref={this.mapContainer} className="map-container" onClick={handleClick.bind(this, layer) />
}
Any guidance is appreciated! Thanks!