diff --git a/main.js b/main.js index a92770e..25c3b06 100644 --- a/main.js +++ b/main.js @@ -3,6 +3,10 @@ import { Map, View } from "ol"; import OSM from "ol/source/OSM.js"; import projectionBNG from "./projection"; import TileLayer from "ol/layer/Tile"; +import getWMTSLayer from "./wmts"; + +// Create layer from imported functions +const mastermapWMTS = await getWMTSLayer("os_licensed_background_colour"); // Set up a new Tile Layer const openStreetMap = new TileLayer({ @@ -15,7 +19,8 @@ const map = new Map({ // This is the HTML element we will target to render our map target: "map", layers: [ - openStreetMap, + // openStreetMap, + mastermapWMTS, ], // A View object represents a simple 2D view of the map. // This is the object to act upon to change the center, resolution, and rotation of the map diff --git a/wmts.js b/wmts.js new file mode 100644 index 0000000..9534d62 --- /dev/null +++ b/wmts.js @@ -0,0 +1,29 @@ +import TileLayer from "ol/layer/Tile"; +import WMTSCapabilities from "ol/format/WMTSCapabilities"; +import WMTS, { optionsFromCapabilities } from "ol/source/WMTS"; + +// Helper function to get a WMTS layer from theMapCloud +const getWMTSLayer = async (layerName) => { + // The first step is to fetch the GetCapabilities document + const response = await fetch("https://api.themapcloud.com/maps/wmts?" + new URLSearchParams({ + request: "GetCapabilities", + service: "WMTS", + token: import.meta.env.VITE_TMC_TOKEN, + })); + // We then parse this... + const parser = new WMTSCapabilities(); + const capabilities = parser.read(await response.text()); + //...so that OL can create a WMTS Options object to configure the layer + const options = optionsFromCapabilities(capabilities, { + layer: layerName, + }); + + // Create the WMTS layer + const wmtsLayer = new TileLayer({ + source: new WMTS(options), + }); + + return wmtsLayer; +}; + +export default getWMTSLayer; \ No newline at end of file