3

I'm using Leaflet i want to show an alert that shows latlng of the clicked location I followed document steps in here https://leafletjs.com/examples/quick-start/

I've tried this

    var mymap = L.map('mapid').setView([51.505, -0.09], 13);

    function onMapClick(e) { //THE FUNCTION
      alert("You clicked the map at " + e.latlng);
      }

  mymap.on('click', onMapClick);

and at <MapContainer> i defined it like

<MapContainer id="mapid" onClick={onMapClick}/>

but it shows nothing

here is the whole code

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'

import React, { Component } from 'react';
import L from 'leaflet'

class UserMap extends Component {

  render() {
    var mymap = L.map('mapid').setView([51.505, -0.09], 13);
    function onMapClick(e) {
      alert("You clicked the map at " + e.latlng);
  }
  mymap.on('click', onMapClick);
    return (
      <div
       id="mapid" style={{ height: '100%', width: '100%' }}>
        <MapContainer
       
          id="mapid"
          center={[30.794900, 50.564580]}
          zoom={13}
          zoomOffset={1}
          boxZoom={false}
          scrollWheelZoom={true}
          style={{ height: '500px', width: '100%' }}>
          <TileLayer
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <Marker 
          position={[30.794900, 50.564580]}>
            <Popup>
              A pretty CSS3 popup. <br /> Easily customizable.
    </Popup>
          </Marker>
        </MapContainer></div>


    );
  }
}

export default UserMap;
joseph smith
  • 143
  • 1
  • 10

1 Answers1

2

onClick is not working anymore, instead you should use the useMapEvents hook (https://react-leaflet.js.org/docs/api-map/#usemapevents).

Basically, you have to create a component with the useMapEvents hook which will listen to the click and call this component in your MapContainer.

Add the following code inside your MapContainer to fix your issue:

function MyComponent() {
    useMapEvents({
        click(e){
            alert(e.latlng)
        }
    })
}
Valentin Briand
  • 3,163
  • 2
  • 8
  • 17
Ensar Kaya
  • 21
  • 2