Skip to content

Instantly share code, notes, and snippets.

@jorandradefig
Last active November 12, 2021 06:22
Show Gist options
  • Select an option

  • Save jorandradefig/bd0eb7d71b23ca0991760acd40f39009 to your computer and use it in GitHub Desktop.

Select an option

Save jorandradefig/bd0eb7d71b23ca0991760acd40f39009 to your computer and use it in GitHub Desktop.
React-Leaflet Add Marker on Click
const React = window.React;
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;
const style = {
map: {
height: '400px',
width: '100%'
}
}
class SimpleExample extends React.Component {
constructor() {
super();
this.state = {
markers: [[19.4100819, -99.1630388]]
};
}
addMarker = (e) => {
const {markers} = this.state
markers.push(e.latlng)
this.setState({markers})
}
render() {
return (
<Map
center={[19.4100819, -99.1630388]}
onClick={this.addMarker}
zoom={13}
style={style.map}
>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
{this.state.markers.map((position, idx) =>
<Marker key={`marker-${idx}`} position={position}>
<Popup>
<span>Popup</span>
</Popup>
</Marker>
)}
</Map>
);
}
}
window.ReactDOM.render(<SimpleExample />, document.getElementById('container'));
@LouieAdauto
Copy link

it tells me that Map is not exported from react-leaflet, what version did you use?

@danieltkach
Copy link

This doesn't work on v3 anymore, right? How do you do it on v3? I just want to catch the click event on the map.

@ondrovic
Copy link

did you ever figure this out? I'm currently stuck trying to get the onClicks to fire for markes

@neel-prajapati
Copy link

@LouieAdauto You can use MapContainer instead of Map (exported as of v3).
@danieltkach For v3, you can utilize the useMap() hook exported from react-leaflet. More on this here.
@ondrovic You can get click events through useMap() hook. Refer the above link:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment