Search code examples
reactjstypescriptleafletreact-leaflet

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


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?


Solution

  • 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>
        )
    }