[英]Add more than one tile layers to <Mapcontainer> in react-leaflet
我想向地图容器添加多个瓦片层。 我无法做到这一点。 我有一个这样的瓷砖层
const magnifiedTiles = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
还有一个在这里:
export default function App(): JSX.Element {
return (
<>
<MapContainer center={center} zoom={13} scrollWheelZoom={true} style={{height: 'calc(100% - 30px)'}}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
/>
</>)
}
我可以从地图容器中获取地图参考并使用类似magnifiedTiles.addTo(<map>)
但我不知道如何获取地图参考。 其他选项是addLayer()
。 但是,我无法从 L.Tilelayer 访问它。
我知道它传单就像获取地图参考和使用map.addLayer()
一样简单。
您可以通过 react-leaflet v.4.x 中的 ref 轻松获取地图参考
const [map, setMap] = useState(null)
<MapContainer
center={center}
zoom={zoom}
scrollWheelZoom={false}
ref={setMap}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
然后使用 useEffect 添加您想要的任何图层。
useEffect(()=> {
if (!map) return ;
map.addLayer(...);
},[])
添加 typescript 标签后进行编辑:与之前相同,只有更改的内容应安装 @types/react-leaflet 并声明 map ref 类型。
import { Map as MapProp, tileLayer } from "leaflet";
...
const streets = tileLayer(
"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}",
{
attribution:
'<a href="https://www.openstreetmap.org/">OpenStreetMap</a>, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: "mapbox/streets-v11",
tileSize: 512,
zoomOffset: -1,
accessToken:
...
}
);
const [map, setMap] = useState<MapProp | null>(null);
...
useEffect(() => {
if (!map) return;
map.addLayer(streets);
}, [map]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.