如何解决React/Leaflet-by-side 错误:地图容器已经初始化 #35
我在使用 useEffect 重新渲染地图时遇到问题
const [baseViewCoords,setBaseViewCoords] = useState([37.715,44.8611]);
const searchApiHandler = () => {
// some code that will fetch new values for baseViewCoords and set to the state
};
useEffect(() => {
var map = L.map('map').setView(baseViewCoords,13);
[](url)
var osmLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap<\/a> contributors'
}).addTo(map);
var stamenLayer = L.tileLayer('https://stamen-tiles-
{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.png',{
attribution:
'Map tiles by <a href="http://stamen.com">Stamen Design<\/a>,' +
'<a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0<\/a> — ' +
'Map data {attribution.OpenStreetMap}',minZoom: 1,maxZoom: 16
}).addTo(map)
L.control.sideBySide(stamenLayer,osmLayer).addTo(map);
},[baseViewCoords]);
return (
<div id="map" />
)
我正在尝试更改地图的位置并在获取 api 后重新渲染它,但显示了附加文件 enter image description here
解决方法
发生这种情况是因为在挂载时,L.map
正在查找 <div id="map" />
并将其初始化为地图。然后,每当您的 useEffect
运行时,它都会尝试使用相同的 div 来运行 L.map
again,但传单识别出该 div 已经是传单映射,因此会出错。
我建议使用实际的 react-leafet 组件:
import { MapContainer,TileLayer } from 'react-leaflet';
const MyComponent = () => {
const [baseViewCoords,setBaseViewCoords] = useState([37.715,44.8611]);
const [map,setMap] = useState();
const searchApiHandler = () => {...};
useEffect(() => {
if (map){
L.control.sideBySide(stamenLayer,osmLayer).addTo(map);
}
},[map])
useEffect(() => {
if (map){
map.setView(baseViewCoords)
}
},[map,baseViewCoords]);
return (
<MapContainer
center={baseViewCoords}
zoom={13}
whenCreated={map => setMap(map)}
>
<TileLayer
url={osm_url}
/>
<TileLayer
url={stamen_url}
/>
</MapContainer>
)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。