This is part 3 (and the last one) of a multi-part React tutorial on Mapbox.
In part 1, we simply focus on displaying a map and adding a geocoder to look up addresses. We even managed to re-center our map to the selected address.
In part 2, we learned how to display markers.
Part 3 will be focusing on popups and removing markers from a map.
_Note: Here is the link to Part 1 in case you missed it. And here is part 2
Let’s get started!
Once again, we will be using the react-map-gl library which offers a nice Popup component. So I will go ahead and create a CustomPopup
component to display the address after clicking on a marker.
import ReactMapGL, {Marker, Popup } from 'react-map-gl';
const CustomPopup = ({index, marker, closePopup}) => {
return (
<Popup
latitude={marker.latitude}
longitude={marker.longitude}
onClose={closePopup}
closeButton={true}
closeOnClick={false}
offsetTop={-30}
>
<p>{marker.name}</p>
</Popup>
)};
Again, thanks to react-map-gl, we get a Popup component which takes lat/long, but also offsetTop
(meaning, in this case, I want the popup to appear on top of the marker).
To make it work, we add need an onClick on our markers called openPopup
. This function will set which marker was clicked thanks to its unique index.
const CustomMarker = ({index, marker, openPopup}) => {
return (
<Marker
longitude={marker.longitude}
latitude={marker.latitude}>
<div className="marker" onClick={() => openPopup(index)}>
<span><b>{index + 1}</b></span>
</div>
</Marker>
)};
And back to our parent component:
constructor(props) {
super(props);
this.state = {
...,
selectedIndex: null,
...
};
}
setSelectedMarker = (index) => {
this.setState({ selectedIndex: index })
}
closePopup = () => {
this.setSelectedMarker(null)
};
openPopup = (index) => {
this.setSelectedMarker(index)
}
render() {
return(
...
{
this.state.markers.map((marker, index) => {
return(
<CustomMarker
key={`marker-${index}`}
index={index}
marker={marker}
openPopup={this.openPopup}
/>
)
})
}
...
)
}
#javascript #mapbox #reactjs #react