Getting started with Leaflet maps
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="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
- Include Leaflet JavaScript file.
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></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 = L.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}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
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: