Map it Out

Michael McGovern
3 min readJun 18, 2019

How to implement an interactive map to your project using the Leaflet JavaScript library.

Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. It is designed with simplicity, performance and usability in mind. It is efficient across mobile and desktop platforms and can be extended with a vast amount of plugins. The library is well documented and has a simple, easy to read source code. The documentation for leaflet can be found here.

Getting Started

For the purposes of this blog, we will be creating a simple project of a full screen interactive map.

To start create a new project directory

mkdir map-it-out

Change directories into the newly created project directory.

cd map-it-out

Create an HTML, CSS, and JavaScript files.

touch index.html

touch index.css

touch index.js

Open up your newly created files in a text editor of your choice.

Initial Set Up

Open up your index.html file and add the basic HTML structure.

Link the CSS and JS file in your HTML file.

Adding Leaflet to your document

Visit leaflet and copy the two lines of code under the “Using a Hosted Version of Leaflet” headline.

Add the two lines of code in the head section of your HTML code.

Now create a “div” element with an id of map so we can later style our map.

Time to style

Open up the index.css file and add some styling for our map. For our map we are going to make it full screen. So we will set the position to relative and give the top, bottom, left and right a value of 0.

Setting Up Our Map

For a full step by step Starting Guide check out here.

We will start off by initializing the map and set the view to a chosen view via geo-coordinates and a zoom level.

To change the view, put new geo-coordinates as the first argument for the setView property, the second argument is the zoom level.

To find geo-coordinates, visit google maps and find the location that you are looking for. You then right click and then click “What’s here?”

A popup window will appear and the geo-coordinates will be at the bottom

Add Tile Layer

Next, we will add a tile layer to our map. Creating a tile layer will set the tile images, the attribution text and the maximum zoom level of the layer.

In this example we will be using MapTiler Cloud. The documentation for MapTiler Cloud can be found here. If you do not have an account you will have to take 2 seconds and sign up in order to get access. Once signed up click on maps, then choose a map style you would like to use. You will need to copy the code for the Raster Tiles and the attribution.

Copy the bottom link

Add the copied code to your JavaScript code.

Add a marker to your map

Add a marker to your map by adding this code to your index.js file.

Now our map is all set up, open index.html from the terminal and have fun mapping out !

--

--