gpt4 book ai didi

javascript - 如何使用 React-leaflet v3 在 map 加载时将 map 设置为地理位置

转载 作者:行者123 更新时间:2023-12-05 02:45:30 27 4
gpt4 key购买 nike

您好,我想加载带有地理位置坐标的 map 。现在我将 map 加载到定义的中心,当事件 onClick 发生时, View 将设置为地理定位位置。我只是希望在我第一次加载 map 时发生这种情况。我的代码如下:

...
const Maps = () => {
// visitor geoLocalisation on the Map
function LocationMarker() {
const [position, setPosition] = useState(null);

const map = useMapEvents({
click() {
map.locate();
},
locationfound(e) {
setPosition(e.latlng);
map.flyTo(e.latlng, map.getZoom());
},
});

return position === null ? null : (
<Marker
position={position}
icon={visitorIcon}
>
<Popup>You are here</Popup>
</Marker>
);
}

return (

<MapContainer
center={[48.856614, 2.3522219]}
zoom={13}
scrollWheelZoom
>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>

<LocationMarker />

</MapContainer>

);
}

最佳答案

useMapEvents 替换为将在组件挂载时触发的 useEffect。使用 map.locate().on("locationfound") 事件触发地理定位。

function LocationMarker() {
const [position, setPosition] = useState(null);

const map = useMap();

useEffect(() => {
map.locate().on("locationfound", function (e) {
setPosition(e.latlng);
map.flyTo(e.latlng, map.getZoom());
});
}, []);

return position === null ? null : (
<Marker position={position} icon={visitorIcon}>
<Popup>You are here</Popup>
</Marker>
);
}

Demo

关于javascript - 如何使用 React-leaflet v3 在 map 加载时将 map 设置为地理位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65979955/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com