Use Mapbox GL JS in a Svelte app
Svelte is a popular JavaScript web framework used for increasing client performance. Since Svelte manipulates the DOM, it can be confusing to connect Svelte with other libraries that also manipulate the DOM and manage state — like Mapbox GL JS.
In this tutorial, you will learn how to create a Svelte web app that uses Mapbox GL JS to render a map, display the coordinates of the map center point and its zoom level, then update the display when a user interacts with the map. You will be able to use the principles discussed in this tutorial to create more complex apps that use both Svelte and Mapbox GL JS. This tutorial shows code for Svelte Bindings and Component Lifecycles.
Getting started
- A Mapbox access token. Your Mapbox access tokens are on your Account page.
- Mapbox GL JS. Mapbox GL JS is a JavaScript library used for building web maps.
- A text editor. Use the text editor of your choice for writing HTML, CSS, and JavaScript.
- Git. You will need to be able to run
git
commands from your command line. - Node.js and npm. To run the commands necessary to run your Svelte app locally, install Node.js and npm.
- Working familiarity with Svelte. You don't need to have a lot of experience using Svelte to complete this tutorial, but you should be familiar with the underlying concepts and workflows.
Set up the Svelte app structure
To get started, clone Svelte's "template" GitHub repository. This will create a base layer to build any Svelte app upon. Wherever you want the folder for this project to exist on your computer, navigate to that directory via the command line and run the following command:
git clone https://github.com/sveltejs/template use-mapbox-gl-js-with-svelte
Then, in your command line, cd
into the new directory use-mapbox-gl-js-with-svelte
and run the following command:
npm install
This will install the dependencies that your app requires, creating the file package-lock.json
and the folder node_modules
.
You also need to install Mapbox GL JS in this project. In the same directory, run the following command:
npm install mapbox-gl
Finally, open the index.html
file in the public
folder in a text editor of your choice. Add the following CSS within the <head>
of the document to make sure your app will use all the space available in the browser window:
<style>
body {
margin: 0;
padding: 0;
}
</style>
Setup is complete and you should have the following file structure:
use-mapbox-gl-js-with-svelte
node_modules
public
favicon.ico
global.css
index.html
scripts
setupTypeScript.js
src
App.svelte
main.js
.gitignore
package-lock.json
package.json
README.md
rollup.config.js
Save your changes.