Adding 'onClick' function to a MapContainer from 'react-leaflet' in typescript file

Viewed 5455

In a Typescript file, I can t import 'Map' from 'react-leaflet' and easily fixed it with 'MapContainer'. However, I need to add an 'onClick' function to it, but 'MapContainer' does not support 'onClick'. I followed the documentation but it led me to new/additional issues... I just need to add a simple onClick function to enable user mark a location with a mouseclick on such map. Anyone knows a simple quick fix?

3 Answers

For those who are still struggling with this, I've just managed to capture that CLICK EVENT IN MAP and (for example, add a marker there). I'm also adding the geolocation example in case you need it too, so:

  • Create a functional component that will handle the layer where events will happen (and also that marker get printed in my case).
  • Instance that func component inside your MapContainer.
import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet';

const SomeComponent = () => {  

    const [initialPosition, setInitialPosition] = useState<[number, number]>([0,0]);
    const [selectedPosition, setSelectedPosition] = useState<[number, number]>([0,0]);

    useEffect(() => {
        navigator.geolocation.getCurrentPosition(position => {
            const { latitude, longitude } = position.coords;
            setInitialPosition([latitude, longitude]);

        });
    }, []);

    ...

    const Markers = () => {

        const map = useMapEvents({
            click(e) {                                
                setSelectedPosition([
                    e.latlng.lat,
                    e.latlng.lng
                ]);                
            },            
        })

        return (
            selectedPosition ? 
                <Marker           
                key={selectedPosition[0]}
                position={selectedPosition}
                interactive={false} 
                />
            : null
        )   
        
    }

    ...

    return(
        <MapContainer 
            center={selectedPosition || initialPosition} 
            zoom={12}                        
        >
            <Markers />
            <TileLayer
                attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />                        
        </MapContainer>
    )
}

I followed the documentation on link and was finally able to make the 'click' event work, and make the 'Marker' render on map. However, it does not point the Marker on selected place on map. It always points the marker on same place on map, and console returns a fixed position(latitude, longitude). I am starting to dislike leaflet.
https://react-leaflet.js.org/docs/example-events/

export default function CreateSomething() {

function LocationMarker() {
 const [ position, setPosition ] = useState({ latitude: 0, longitude: 0 })
  
  const map = useMapEvents({
    click() {
      map.locate()
    },
    locationfound(e) {
      const { lat, lng } = e.latlng;
         setPosition({
            latitude: lat,
            longitude: lng,
          })
      map.flyTo(e.latlng, map.getZoom())
    },
  })

  return (
      position.latitude !== 0 ? 
      <Marker 
        position={[position.latitude, position.longitude]}
        interactive={false} 
        icon={happyMapIcon} 
        />

       : null
  )   
  
}
return (

     <MapContainer  
       <LocationMarker />
     </MapContainer>
     
     )
  }   

function AddMarkerToClick() {
const [position, setPosition] = useState({ latitude: 0, longitude: 0 });

const map = useMapEvents({
  click(event) {
    const { lat, lng } = event.latlng;
    setPosition({
      latitude: lat,
      longitude: lng,
    });
  },
});

return (
  position.latitude !== 0 ? (
    <Marker
      position={[position.latitude, position.longitude]}
      interactive={false}
      icon={mapIcon}
    />
  ) : null

); }

Related