Introduction to LeafletJS

In recent years, web mapping has become an essential part of various web applications. One of the popular libraries for web mapping is Leaflet.js. Leaflet is a leading open-source JavaScript library for mobile-friendly interactive maps. In this blog post, we will explore Leaflet.js with some of its basic features and how we can use it to create interactive maps.
Why LeafletJS?
Now one question arises is why we need to use Leaflet if we have some other map libraries like Google Map. So below are some reasons describing why we should use LeafletJS:
- Open source and free: Leaflet is an open source library. You can use it without paying anything. As in google map we have to pay as we use.
- All basic features: Leaflet provides all basic features of map like rendering a map, adding a marker to the map, annotations on map etc.
- Many supporting plugins: If there is some feature which is not present in Leaflet core library like Geolocation, for this it has some supporting libraries which you can use to have some basic working of that feature. Obviously, it will not be that good as compared to google maps but it should allow some basic working.
- Support: Leaflet supports all major browsers like Chrome, Brave, Mozilla etc.
- Easy to use: As compared to google maps, in which you have to get an api key first to use it, Leaflet is very easy to use, requiring just installing a npm module or just importing a cdn.
Installation:
Below are two ways in which you can use Leaflet in your code:
- CDN: You have to import a Leaflet script and CSS file in your code, then you are good to go.
Script:
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>
CSS Link:
- NPM: We can also use the leaflet npm module, npm i leaflet
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
How to use Leaflet?
Now we have seen how to import leaflets but the question arises is how to use it. So below are the steps by which you can create a map with leaflet.
- First you need to import cdn via cdn or npm module.
- Create a div in your html with some id, as we need to provide leaflet a container in which the map needs to be rendered. The div should have some dimensions.
- Leaflet needs a tile layer of a map (image of image). It will be a url of the tile layer from which leaflet will fetch map images and render them to form a map.
Below is a basic JS code for a simple Leaflet map:
var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
In the above code:
- L will be available for you globally as the base Leaflet object containing all the methods.
- ‘map’ is the id of the html container.
- setView is used to set an initial view for the map with first argument as lat and lng for the initial view and second argument as zoom level.
- L.tileLayer is used to set the titleLayer to the map.
Below is a basic image of how it will look:
Features
In this section some of the core and basic features of Leaflet
Tile Layer
A tile layer is a set of web-accessible tiles that reside on a server. The tiles are accessed by a direct URL request from the web browser. Leaflet displays a map by displaying a series of tiles across the page. It needs to know where to get these tiles from and how the tiles are stored in a directory structure. We can set a tile like:
var layer = L.tileLayer('URL of the required map tile');
To load the required tile layer for the map, we can choose from various service providers such as Open street map, mapbox, Thunder forest, ESRI etc.
Example Layers:
- http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png
- http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png
- http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/ {y}.png
Markers and Popup
Markers are used to mark a single location over the map using some icon or images, leaflet provides markers. Markers use a symbol which can be customized.
var marker = L.marker([16.385, 75.4866]); marker,addTo(map);
Popup, on the other hand, is used to provide additional information when a marker or another element on the map is clicked. So, before adding the marker to the map like in above code, we have to do
marker.bindPopup(‘Hi I am a popup’);
In the end add the marker to the map with the addTo method.
Vector Shapes
In Leaflet.js, vector shapes can be used to draw various shapes like circles, rectangles, polygons, and polylines on a map. These shapes are vector objects that can be styled using various properties such as color, weight, and opacity. Vector shapes can also be used to add interactivity to a map, such as attaching popups and click events. Overall, vector shapes in Leaflet.js provide a flexible and powerful way to create custom maps with various shapes and styles.
Below example shows how to create a polyline and add it to the map:
var latlngs = [ [17.385044, 78.486671], [16.506174, 80.648015], [17.000538, 81.804034], [17.686816, 83.218482] ]; var polyline = L.polyline(latlngs, {color: ‘red’}); polyline,addTo(map);
We have to give some coordinates (lat/lng) for the positions of the polyline. Same as polyline we can create other shapes.
Ref: https://leafletjs.com/reference-1.7.1.html#path
Events
Events in Leaflet.js refer to various user interactions such as clicking, dragging, zooming, and panning on a map. We can register event listeners on various map objects such as markers, pop ups, and layers to capture specific events and perform actions in response to them.
Below is an example in which we are adding a marker when a user clicks on the map.
map.on(“click”, function (e) { new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map); });
Controls
In Leaflet.js, controls refer to various UI elements that can be added to a map to provide additional functionality and interactivity. Leaflet provides various controls like zoom, attributions, scale.
- Zoom: This control, by default, exists at the top left corner of the map. It has two buttons ‘+’ and ‘-’ to zoom in and zoom out the map. We can remove the default control and set our own like below
- Attribution: This control, by default, exists at the bottom right corner of the map. It displays the attribution data.
- Scale: This control, by default, exists at the bottom left corner of the map. It displays the current center of the map.
var zoomControl = L.control.zoom(zOptions); var attrControl = L.control.attribution(aOptions); var scaleControl = L.control.scale();
Conclusion
So, above we have seen how interesting and fascinating LeafletJS is. Maybe it’s not as powerful as google maps but it provides some good features for a map integration for our app and all free. It provides a simple system. Its extensive documentation allows developers of any level to create interactive maps in no time. I personally would suggest every developer who is looking for a Map library to give Leaflet a shot.
Author: Nipun Jain