Last active
November 12, 2021 06:22
-
-
Save jorandradefig/bd0eb7d71b23ca0991760acd40f39009 to your computer and use it in GitHub Desktop.
React-Leaflet Add Marker on Click
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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='© <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')); |
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.
did you ever figure this out? I'm currently stuck trying to get the onClicks to fire for markes
@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
it tells me that Map is not exported from react-leaflet, what version did you use?