如何解决如何使用 React-leaflet v3 在地图加载时将地图设置为地理位置
您好,我想加载带有地理位置坐标的地图。 现在我将我的地图加载到一个定义的中心,当 onClick 事件发生时,视图被设置为地理定位位置。 我只是希望在我第一次加载地图时发生这种情况。 我的代码如下:
...
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='© <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>
);
}
,
所以最后我将 map 放在依赖项中并添加了一个 clenaup 函数来避免 Eslint 并响应上面的警告。
function LocationMarker() {
const [position,map.getZoom());
});
return function cleanup() {
map.stopLocate();
};
},[map]);
return position === null ? null : (
<Marker position={position} icon={visitorIcon}>
<Popup>You are here</Popup>
</Marker>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。