I want to display a very basic map with mapbox using svelte.
I am already failing when I just want to make the map full screen. I know there is the svelte-mapbox plug in. But I really do not want to do any fancy things. Just a full screen map for now;)
So my main.js looks defaultish like this:
import App from "./App.svelte";
const app = new App({
target: document.body,
});
export default app;
The App.svelte like this:
<script>
import mapboxgl from "mapbox-gl";
mapboxgl.accessToken = 'token'
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/light-v10",
center: [16.37, 48.2],
zoom: 12,
});
</script>
<svelte:head>
<link
href="https://api.mapbox.com/mapbox-assembly/v0.23.2/assembly.min.css"
rel="stylesheet"
/>
<script
src="https://api.mapbox.com/mapbox-assembly/v0.23.2/assembly.js"></script>
</svelte:head>
<div id="map" />
<style>
div {
width: 100%;
height: 100%;
}
</style>
And thats it. Nothing is appearing. If I add:
...
<body>
<div id="map"></div>
</body>
...
This to the `index.html, then I see this:
The problem is that when the Javascript of your component runs then the <DIV id="map"/> is not created yet. So the Mapbox call won't find a container to put the map into, and just quits.
When you put the <DIV id="map"/> in your index.html then the DIV was there but because of the CSS scoping of Svelte the CSS wasn't applied to it (because it's outside of your component) (see: https://svelte.dev/docs#style)
You can use the :global modifier in the CSS declaration to "fix" that and it should work.
But the better solution is to have the map creation code run at the correct part of the component life cycle: after the HTML is mounted in the DOM.
To do that you would need to use the onMount function from the Svelte library: (see: https://svelte.dev/docs#onMount)
import { onMount } from 'svelte'
import mapboxgl from "mapbox-gl";
mapboxgl.accessToken = 'token'
onMount(() => {
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/light-v10",
center: [16.37, 48.2],
zoom: 12,
});
})