[英]Adding 'onClick' function to a MapContainer from 'react-leaflet' in typescript file
在 Typescript 文件中,我無法從“react-leaflet”導入“Map”並使用“MapContainer”輕松修復它。 但是,我需要為其添加一個“onClick”函數,但“MapContainer”不支持“onClick”。 我遵循了文檔,但它讓我遇到了新的/額外的問題......我只需要添加一個簡單的 onClick 函數,讓用戶在這樣的地圖上用鼠標點擊標記一個位置。 任何人都知道一個簡單的快速修復?
我按照鏈接上的文檔進行操作,終於能夠使“單擊”事件起作用,並使“標記”在地圖上呈現。 但是,它不會將標記指向地圖上選定的地點。 它總是將標記點在地圖上的同一位置,控制台返回一個固定位置(緯度、經度)。 我開始不喜歡傳單了。
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> ) }
對於那些仍在為此苦苦掙扎的人,我剛剛設法在地圖中捕獲了該點擊事件(例如,在那里添加了一個標記)。 我還添加了地理定位示例,以防您也需要它,因此:
import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet';
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='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
)
}
順便說一句,stackoverflow 的 [代碼解析器] 到底是怎么回事???
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
); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.