Getting started with Leaflet maps

27 / Jun / 2016 by Arpit Jain 0 comments

Leaflet is a open source Javascript library that can be used to create interactive maps. It comes with all mapping features that most of us need in any project like adding markers,  popups, vector layers, zooming, selecting lat-lng of a place and much more.

In this blog, we will learn how to get started with Leaflet maps and we will also do some stuffs like adding markers and popups.

Setting up your page

  • In the head section of your html page include Leaflet CSS file.
           <link rel="stylesheet" href="" />
  • Include Leaflet  JavaScript file.
          <script src=""></script>
  • Add div Element with some Id in which you want to render your map.
          <div id="myMap"></div>
  • Make sure your map container has a defined height. You can use CSS like this:
          #myMap { height: 250px; }

Now, let’s start with initializing the map.

Initializing the map

First, initialize your map and set its view to some geographical coordinates and a zoom level.

var map ='myMap').setView([51.505, -0.09], 13);// center of London with zoom level 13

Next, add a tile layer to map, in this case OpenStreetMap tile layer. Adding a tile layer involves setting the URL template for the tile images and the attribtution :

L.tileLayer('http://{s}{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="">OpenStreetMap</a> contributors'

Make sure all these lines of code is called after the div and the javascript file leaflet.js inclusion. Now, map will get rendered inside your map container.

Adding marker

Marker can easily be added by setting lat-lng. Let’s add a marker:

     var marker = L.marker([51.5, -0.09]).addTo(map);

Adding popups

Popups are used when you want to add some additional information with an object on the map. Attaching popup to objects is very simple in Leaflet:

    marker.bindPopup("<strong>Hello world!</strong><br>I am a popup.").openPopup();

After, doing all the above stuffs your final map will look something like this:



Leave a comment -