Setup Maplibre and Terra Draw
Open terradraw-workshop-template project on your vscode, and open a terminal.
Install dependencies
pnpm install -D maplibre-gl terra-draw terra-draw-maplibre-gl-adapter
Setup a blank Maplibre map
Find +page.svelte file under src/route folder, and open it on vscode.
Delete the following default HTML.
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p>
Paste the following code to +page.svelte.
<script lang="ts">
import {
AttributionControl,
GeolocateControl,
GlobeControl,
Map,
NavigationControl,
ScaleControl
} from 'maplibre-gl';
import { onMount } from 'svelte';
import 'maplibre-gl/dist/maplibre-gl.css';
let mapContainer: HTMLDivElement | undefined = $state();
let map: Map | undefined = $state();
onMount(() => {
if (!mapContainer) return;
map = new Map({
container: mapContainer,
style: {
version: 8,
name: 'OpnenStreetMap Raster',
sources: {
osm: {
type: 'raster',
tiles: ['https://tile.openstreetmap.jp/{z}/{x}/{y}.png'],
tileSize: 256,
maxzoom: 19,
attribution:
'<a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>'
}
},
layers: [
{
id: 'osm',
type: 'raster',
source: 'osm'
}
]
},
center: [174.7629, -36.8587],
zoom: 11,
hash: true,
attributionControl: false
});
map.addControl(new NavigationControl(), 'top-right');
map.addControl(new GlobeControl(), 'top-right');
map.addControl(
new GeolocateControl({
positionOptions: { enableHighAccuracy: true },
trackUserLocation: true
}),
'top-right'
);
map.addControl(new ScaleControl({ maxWidth: 80, unit: 'metric' }), 'bottom-left');
map.addControl(new AttributionControl({ compact: true }), 'bottom-right');
});
</script>
<div class="main">
<aside class="sidebar">
</aside>
<div class="map" bind:this={mapContainer}></div>
</div>
<style lang="scss">
.main {
display: flex;
height: 100vh;
width: 100vw;
.sidebar {
width: 260px;
background: #f4f4f4;
border-right: 1px solid #ddd;
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
}
.map {
flex: 1;
height: 100%;
width: 100%;
}
}
</style>
Disable SSR
As default setting of SvelteKit, the above code cannot work with SSR.
Add +page.ts under src/routes folder and paste the below script.
export const ssr = false;