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.
[code language=”javascript”]
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
[/code]
- Include Leaflet JavaScript file.
[code language=”javascript”]
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
[/code]
- Add div Element with some Id in which you want to render your map.
[code language=”javascript”]
<div id="myMap"></div>
[/code]
- Make sure your map container has a defined height. You can use CSS like this:
[code language=”javascript”]
#myMap { height: 250px; }
[/code]
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.
[code language=”javascript”]
var map = L.map(‘myMap’).setView([51.505, -0.09], 13);// center of London with zoom level 13[/code]
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 :
[code language=”javascript”]
L.tileLayer(‘http://{s}.tile.osm.org/{z}/{x}/{y}.png’, {
attribution: ‘© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors’
}).addTo(map);
[/code]
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:
[code language=”javascript”]
var marker = L.marker([51.5, -0.09]).addTo(map);
[/code]
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:
[code language=”javascript”]
marker.bindPopup("<strong>Hello world!</strong><br>I am a popup.").openPopup();
[/code]
After, doing all the above stuffs your final map will look something like this: