Use data files to import existing data or have an easy way of managing global data in this SvelteKit tutorial.
In this final lesson, we’ll put everything together to create a page with a map which lists top dog parks. We’ll generate a
.json file which contains the location and other metadata for a dog walk, then another file which fetches the
.json file and renders the map. Let’s get to it!
All the metadata for the park — the name, latitude and longitude — needs to live somewhere. We’re going to store it in a static JSON file to keep things simple. Create
/static/locations.json with the following content:
We’re going to create a reusable component that we can use anywhere on the site to output our favorite dog parks. We’re using a library called Leaflet to create the map and markers so we’ll install the dependencies for this first. In your terminal run:
With leaflet installed, we can put it to work. Let’s create a new Map component at
/src/lib/Map.svelte with the following:
I’ll break this down so you can understand what’s going on here.
First, we’re importing two scripts:
So all of this ensures, we’re in the right environment and we’re ready to initalize the map:
Now we need to get our locations, so we fetch them from the
.json file we created earlier:
Then we import the leaflet library and initialize the map:
Then we’re adding the markers and setting the bounds so the map is centered and zoomed in on the markers:
We have to include the styles which we’re adding straight to the
Add the element that holds the map:
And finally add some basic styles:
Phew! Take a look at your hard work and admire the beautiful map you’ve created.
Congratulations on becoming a SvelteKit beginner! You should have a high level understanding of many of the concepts in the framework which will provide a solid foundation to build upon. To continue your journey into the world of SvelteKit, there are a number of great resources I recommend:
Finally I want to briefly mention CloudCannon — it’s a content management system with first-class support for SvelteKit. It syncs directly with your Git repository, so your development team can continue working in SvelteKit while your content team can manage the content on the site. It’s the best of both worlds.
Thanks for reading and keep on building with SvelteKit!