簡體   English   中英

將多個切片圖層添加到<Mapcontainer>在反應傳單中

[英]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='&copy; <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='&copy; <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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM