Leaflet: Getting Started

0

Leaflet is a new and modern JavaScript library capable of catering to both mobile and desktop platform.

Let’s gets started on our very first Leaflet project together. The aim of this guide is to teach you how to:

  • Implement Leaflet
    • Pre-Setup
    • Adding tile layer (MapBox)

Pre-Requisite

Let’s get started! Download the following files and tools.

  1. Leaf.js – Download
  2. MapBox Account – Register
  3. A text editor – Notepad++

Getting Started

MapBox

Head over to MapBox and login to your account.

  1. Create a new project
  2. Click Save
    MapBox Save Map
  3. Click Project and copy your Share link.
    MapBox User Url
  4. Next we have to edit the link that you have just copied. Your link should look something like this:
    You have to replace page.html with {z}/{x}/{y}.png

Implementing Leaflet & MapBox

Loading Leaflet Essentials

First off have to link Leaflet CSS and JS files that we have downloaded into the HTML page. This could be done by adding the following codes in to the <head> section.

Creating the map

  1. Now we have to create a container for Leaflet to load the map in. We will to do this by creating a div with the id “map”. Type or copy the following codes into the <body> section.

    We have to manually set the height of the div or else the map would not be shown later.

  2. As we already have the container of the map. Now we have to load the contents of the container which is the map itself. We have to use the link that we have edited previously from MapBox and some javascript to load the map.Insert your MapBox share link which you have edited in to the following:

  3. Copy the code you have edited to the line just before the </body> tag.
  4. Your HTML file should look like this:

  5. If all goes well you should see the map!
    MapBox Map Result

If you’re a beginner web developer good job! But if you’re a seasoned web developer you should find this a walk in the park. In our next guide we will be going through how to use Leaflet default features:

  • Position + Zoom level
  • Adding markers
  • Popups
  • Implementing events

See you then!

You can download the files created in this guide here: Leaflet-Getting-Started

 

Share.

Leave A Reply