Getting started with Leaflet

9 min read

(For more resources related to this topic, see here.)

Getting ready

First, we need to get an Internet browser, if we don’t have one already installed. Leaflet is tested with modern desktop browsers: Chrome, Firefox, Safari 5+, Opera 11.11+, and Internet Explorer 7-10. Internet Explorer 6 support is stated as not perfect but accessible. We can pick one of them, or all of them if we want to be thorough.

Then, we need an editor. Editors come in many shapes and flavors: free or not free, with or without syntax highlighting, or remote file editing. A quick search on the Internet will provide thousands of capable editors. Notepad++ ( for Windows, Komodo Edit ( for Mac OS, or Vim ( for Linux are among them.

We can download Leaflet’s latest stable release (v0.5.1 at the time of writing) and extract the content of the ZIP file somewhere appropriate. The ZIP file contains the sources as well as a prebuilt version of the library that can be found in the dist directory.

Optionally, we can build from the sources included in the ZIP file; see this article’s Building Leaflet from source section.

Finally, let’s create a new project directory on our hard drive and copy the dist folder from the extracted Leaflet package to it, ensuring we rename it to leaflet.

How to do it…

Note that the following code will constitute our code base throughout the rest of the article.

  1. Create a blank HTML file called index.html in the root of our project directory.

  2. Add the code given here and use the browser installed previously to execute it:

    <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="leaflet/ leaflet.css" /> <!--[if lte IE 8]> <link rel="stylesheet" type="text/css" href=" leaflet/" /> <![endif]--> <script src = "leaflet/leaflet.js"></script> <style> html, body, #map { height: 100%; } body { padding: 0; margin: 0; } </style> <title>Getting Started with Leaflet</title> </head> <body> <div id="map"></div> <script type="text/javascript"> var map ='map', { center: [52.48626, -1.89042], zoom: 14 }); L.tileLayer('http://{s}{z}/ {x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); </script> </body> </html>

The following screenshot is of the first map we have created:

How it works…

The index.html file we created is a standardized file that all Internet browsers can read and display the contents. Our file is based on the HTML doctype standard produced by the World Wide Web Consortium (W3C), which is only one of many that can be used as seen at Our index file specifies the doctype on the first line of code as required by the W3C, using the <!DOCTYPE HTML> markup.

We added a link to Leaflet’s main CSS file in the head section of our code:

<link rel="stylesheet" type="text/css" href="leaflet/leaflet.css" />

We also added a conditional statement to link an Internet Explorer 8 or lower only stylesheet when these browsers interpret the HTML code:

<!--[if lte IE 8]> <link rel="stylesheet" type="text/css" href="leaflet/" /> <![endif]-->

This stylesheet mainly addresses Internet Explorer specific issues with borders and margins.

Leaflet’s JavaScript file is then referred to using a script tag:

<script src = "leaflet/leaflet.js"></script>

We are using the compressed JavaScript file that is appropriate for production but very inefficient for debugging. In the compressed version, every white space character has been removed, as shown in the following bullet list, which is a straight copy-paste from the source of both files for the function onMouseClick:

  • compressed:

    _onMouseClick:function(t){!this._loaded||this.dragging&& this.dragging.moved()||("preclick"),this._ fireMouseEvent(t))},

  • uncompressed:

    _onMouseClick: function (e) { if (!this._loaded || (this.dragging && this.dragging.moved())) { return; }'preclick'); this._fireMouseEvent(e); },

To make things easier, we can replace leaflet.js with leaflet-src.js—an uncompressed version of the library.

We also added styles to our document to make the map fit nicely in our browser window:

html, body, #map { height: 100%; } body { padding: 0; margin: 0; }

The <div> tag with the id attribute map in the document’s body is the container of our map. It must be given a height otherwise the map won’t be displayed:

<div id="map" style="height: 100%;" ></div>

Finally, we added a script section enclosing the map’s initialization code, instantiating a Map object using the…) constructor and a TileLayer object using the L.tileLayer(…) constructor. The script section must be placed after the map container declaration otherwise Leaflet will be referencing an element that does not yet exist when the page loads.

When instantiating a Map object, we pass the id of the container of our map and an array of Map options:

var map ='map', { center: [52.48626, -1.89042], zoom: 14 });

There are a number of Map options affecting the state, the interactions, the navigation, and the controls of the map. See the documentation to explore those in detail at

Next, we instantiated a TileLayer object using the L.tileLayer(…) constructor and added to the map using the TileLayer.addTo(…) method:

L.tileLayer('http://{s}{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map);

Here, the first parameter is the URL template of our tile provider—that is OpenStreetMap— and the second a noncompulsory array of TileLayer options including the recommended attribution text for our map tile’s source.

The TileLayer options are also numerous. Refer to the documentation for the exhaustive list at

There’s more…

Let’s have a look at some of the Map options, as well as how to build Leaflet from source or use different tile providers.

More on Map options

We have encountered a few Map options in the code for this recipe, namely center and zoom. We could have instantiated our OpenStreetMap TileLayer object before our Map object and passed it as a Map option using the layers option. We also could have specified a minimum and maximum zoom or bounds to our map, using minZoom and maxZoom (integers) and maxBounds, respectively. The latter must be an instance of LatLngBounds:

var bounds = L.latLngBounds([ L.latLng([52.312, -2.186]), L.latLng([52.663, -1.594]) ]);

We also came across the TileLayer URL template that will be used to fetch the tile images, replacing { s} by a subdomain and { x}, {y}, and {z} by the tiles coordinate and zoom. The subdomains can be configured by setting the subdomains property of a TileLayer object instance.

Finally, the attribution property was set to display the owner of the copyright of the data and/or a description.

Building Leaflet from source

A Leaflet release comes with the source code that we can build using Node.js. This will be a necessity if we want to fix annoying bugs or add awesome new features.

The source code itself can be found in the src directory of the extracted release ZIP file. Feel free to explore and look at how things get done within a Leaflet.

First things first, go to and get the install file for your platform. It will install Node.js along with npm, a command line utility that will download and install Node Packaged Modules and resolve their dependencies for us. Following is the list of modules we are going to install:

  • Jake: A JavaScript build program similar to make

  • JSHint: It will detect potential problems and errors in JavaScript code

  • UglifyJS: A mangler and compressor library for JavaScript

Hopefully, we won’t need to delve into the specifics of these tools to build Leaflet from source.

So let’s open a command line interpreter— cmd.exe on Windows, or a terminal on Mac OSX or Linux—and navigate to the Leaflet’s src directory using the cd command, then use npm to install Jake, JSHint and UglifyJS:

cd leaflet/src npm install –g jake npm install jshint npm install uglify-js

We can now run Jake in Leaflet’s directory:


What about tile providers?

We could have chosen a different tile provider as OpenStreetMap is free of charge but has its limitations in regard of a production environment. A number of web services provide tiles but might come at a price depending on your usage: CloudMade, MapQuest.

These three providers serve tiles use the OpenStreetMap tile scheme described at

Remember the way we added the OpenStreetMap layer to the map?

L.tileLayer('http://{s}{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map);

Remember the way we added the OpenStreetMap layer to the map?

  • Cloudmade:

    L.tileLayer(' http://{s}{z}/ {x}/{y}.png', { attribution: ' Map data © <a href="http://openstreetmap. org">OpenStreetMap</a> contributors, <a href="http://">CC-BY-SA</a>, Imagery © <a href="">CloudMade</a>' }).addTo(map);

  • MapQuest:

    L.tileLayer('http://{s}{z}/{x}/{y}. png', { attribution: ' Tiles Courtesy of <a href="http://www.mapquest. com/" target="_blank">MapQuest</a> <img src = "http://developer.">', subdomains: ['otile1', 'otile2', 'otile3', 'otile4'] }).addTo(map);

You will learn more about the Layer URL template and subdomains option in the documentation at

Leaflet also supports Web Map Service (WMS) tile layers—read more about it at—and GeoJSON layers in the documentation at


In this article we have learned how to create map using Leaflet and created our first map. We learned about different map options and also how to build a leaflet from source.

Resources for Article :

Further resources on this subject:


Please enter your comment!
Please enter your name here