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

Categories

0 votes
2.0k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...