Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

reactjs - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...