1. Vectortile Map
When starting a project using the template, the base map is created by initializing the MapLibre
instance with a style.json
file. Alternatively, the base map can be implemented using a vector tile layer
. This method allows for runtime adjustments to the background style without the need to refresh the entire style
property of the MapLibre
instance.
-
Comment Out the Style Property: In the
src/App.tsx
file, comment out thestyle
property within theoptions
attribute of theMapLibreMap
component.<MapLibreMap
options={{
//style: "https://wms.wheregroup.com/tileserver/style/osm-bright.json",
zoom: 4,
}}
style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }}
/> -
Add mapId, center and adjust zoom:
<MapLibreMap
mapId="map_1"
options={{
zoom: 5,
center: [10.447683, 51.163361],
//style: "https://wms.wheregroup.com/tileserver/style/osm-bright.json",
}}
style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }}
/> -
Create a New Component File: Establish a new file at
src/components/Layers.jsx
. -
Define a State Variable: Initiate a
state
variable namedbgLayerState
as follows:import { useState } from "react";
import { useEffect, useState } from "react";
export default function Layers() {
const [bgLayerState, setBgLayerState] = useState({
url: "https://wms.wheregroup.com/tileserver/tile/tileserver.php?/europe-0-14/index.json?/europe-0-14/{z}/{x}/{y}.pbf",
layerId: "openmaptiles",
});
return <></>;
} -
Fetch Background Style: Utilize a fetch operation within the initialization effect to acquire the background style from the specified URL. And insert the
layers property
from the fetched style.json into thelayers
property of thestate
variable:fetch("https://wms.wheregroup.com/tileserver/style/osm-bright.json")
.then((response) => response.json())
.then((data) => {
setBgLayerState((current) => {
return { ...current, layers: data.layers };
});
}); -
Include the MlVectorTileLayer Component: In the JSX, add the MlVectorTileLayer component. Use the spread operator to pass all properties of the bgLayerState variable as attributes to the component:
return<>{bgLayerState.layers && <MlVectorTileLayer {...bgLayerState} />;}</>;
-
Import and Use the New Component:
import Layers from "./components/Layers"
insrc/App.tsx
and render it within the application's JSX.
