Leaflet is a free, open source mapping library for creating responsive maps. It has all the features you need to create interactive mobile-friendly maps for the web.
Thanks to its simple and well-documented API, you can easily get up and running, irrespective of your skill level. Leaflet is also data provider agnostic. You can source map tiles from third-party providers such as OpenStreetMap.
In this article, we’ll explore the many features and benefits that make Leaflet a great choice if you’re working on a project that requires interactive, aesthetically pleasing maps. We’ll also compare it to other popular mapping libraries to help inform your decision.
Leaflet is a free, open source JavaScript library for creating interactive and responsive maps for the web. It was created by Vladimir Agafonkin and was first released in 2011.
This lightweight, feature-rich, BSD 2-clause licensed library that supports all the features a map will almost always need. It has built-in support for panning, zooming, markers, popups and tooltips. If the feature you need is not built into Leaflet, most likely, there is a third-party plugin for it.
With Leaflet, you can create a map with all the mapping features you need in a few lines of code:
const map = L.map("map").setView([50.5, 7.5], 13); L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>', }).addTo(map);
You can access its source code via the CDN or use one of the available third-party packages if you want to integrate Leaflet with frontend frameworks such as React or Vue.
Be aware that Leaflet is just a JavaScript library. You still need to get the map tiles from third-party tile providers like OpenStreetMap.
When choosing a framework or library, project requirements such as the application type (web, mobile, desktop), the skills and experience of the development team, and the project’s scale and complexity take center stage.
However, there are additional considerations when choosing a particular framework or library. In this section, we will explore some of them and use them to highlight why you should or should not use Leaflet.
A vibrant community is vital for the development, success, and sustainability of an open source software project. It fosters rapid project development, knowledge sharing, and user support.
Leaflet has a vibrant community of developers and users. Though created by an individual, its current development and maintenance is mainly driven by a community of users and developers. Such an active community inspires confidence in Leaflet’s future and sustainability.
You need to consider the pricing and license requirements of a package when choosing an open source project. The license specifies the terms and conditions under which you use, modify, and distribute the source code.
Leaflet is a BSD-2 clause licensed project. It’s free to use, and the BSD-2 clause license gives you the liberty to use, modify, and re-distribute the source code.
Good documentation makes it easy to pick up a project. As a result, improving development experience. Therefore, before choosing an open source project, consider the availability and quality of its documentation.
Leaflet has a comprehensive and easy-to-understand documentation. Its core API and plugins are well documented too, making it very easy to pick up and start using right away.
Before choosing a package, you need to evaluate its ease of use and learning curve. A package that is difficult to pick up can negatively impact developer experience and hinder development speed.
As explained above, Leaflet focuses on the core mapping features that you will almost always use in a map. Therefore, it has a minimal API with gentle learning curve. You will pick it up almost instantly no matter your skill level.
Leaflet has been widely adopted and is currently under active development. Therefore, you can be sure of regular updates and security patches. The wide adoption and vibrant community should give you confidence about the security of Leaflet.
Though Leaflet’s source code may be secure, you need to be aware that the map tiles you use with Leaflet are mainly from third-party providers like OpenStreetMap. Ensure that your third-party tile provider has taken the appropriate security measures to avoid exposing your application to security vulnerabilities.
If you’re using a third-party Leaflet plugin, you should also ensure that it’s secure and up-to-date.
One of the benefits of Leaflet is that its bundle size is a scant 42 KB in gzipped form. This is a small bundle size compared to all the features and benefits it delivers. It also offers several internal performance optimizations.
However, you are likely to encounter a performance downgrade if you display several markers on a map.
Before picking a particular library, you need to evaluate how easy it is to integrate with the already existing tools, frameworks and libraries.
You can easily integrate Leaflet with popular front-end frameworks such as React, Angular, and Vue either directly or using third-party packages.
There are several desktop and mobile browsers. When choosing a library for a web application, you need to consider browser support. Leaflet is supported in all the modern web browsers.
Getting started with Leaflet is easy. You can access it via a CDN or use third-party integrations for frontend frameworks like React. Follow the steps below to start using Leaflet in vanilla JavaScript via a CDN.
You can start by adding the Leaflet CSS styles to your HTML’s head
element like so:
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
After adding the Leaflet styles as described in the previous subsection, add the script
tag below to your HTML’s head
element:
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin="" ></script>
You can now create an HTML div
container for your map and add it to the document’s body
element:
<div id="map" class="map"></div>
You need to assign the map container a fixed height either using inline styles or an external stylesheet:
.map { height: 500px; }
That is all you need to start using Leaflet. Leaflet will be added to the window
object.You can access it via the variable L
. We will now create a basic Leaflet map in the following sub-sections.
After adding links to the necessary files and creating a container for the map as described above, you can now create a Leaflet map. Add the code below at the end of the body
element (just before the closing </body>
tag) using a script
tag:
const map = L.map("map").setView([50.5, 7.5], 13); L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>', }).addTo(map);
The code above will initialize the map and set its center in central Europe. It also sets the initial zoom level to 13. You can change them to your preferred values. The map will look like the image below:
The above example loads the tile layers from OpenStreetMap. Leaflet is agnostic regarding the map data provider. If you’d prefer, you can use tiles from other providers.
Similarly, we used the unpkg
CDN in the example above. Several other popular CDNs like cdnjs.com
and jsdelvir.com
also host Leaflet. You can use them instead of unpkg
.
To remain lightweight, Leaflet focuses on the core mapping features you will almost always need. In addition to the built-in features, Leaflet has an extensive collection of plugins within its ecosystem. You can also write your own plugin if the functionality you need is not available in the plugin ecosystem.
Let’s explore some of the main built-in Leaflet features you will most likely use in your project. They are very useful for adding interactivity to your map.
Layers are the basic building blocks for interactive maps in Leaflet. It includes tiles, popups, markers, circles, and polygons.
As explained above, you can add a tile layer to Leaflet from a third-party tile provider like OpenStreetMap. Leaflet doesn’t have its own map imagery:
const map = L.map("map").setView([50.5, 7.5], 13); L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>', }).addTo(map);
Leaflet also has a built-in method for creating a group of tile layers and a control UI to switch between them. We will explore the other Layers in the following sub-sections.
Markers come in handy if you are looking to draw emphasis to specific locations or features on a map. In Leaflet, you can use the built-in Marker
method to draw markers. It takes the geographical coordinates of the marker as first argument and an optional object as second argument:
const marker = L.marker([50.5, 7.5]).addTo(map);
The above example will add a marker at the center of the map. The blue pin is the default image if you don’t pass a custom image to the marker
function:
You can use your own image to display a custom marker. Use the built-in icon
function to create a custom icon and display it using the marker
function like so:
const icon = L.icon({ iconUrl: "icon.svg", shadowUrl: "icon-shadow.svg", iconSize: [20, 20], shadowSize: [20, 20], }); const marker = L.marker([50.5, 7.5], { icon: icon, }).addTo(map);
The code above will display a custom image at the specified coordinates.
Instead of using images, you can use other shapes such as circles and polygons to draw attention to specific coordinates or features on the map.
Adding a circle is similar to adding an image marker. However, you need to specify the fill color and the radius of the circle in meters:
const circle = L.circle([50.5, 7.5], { color: "blue", fillColor: "blue", radius: 500, }).addTo(map);
The code above will add a blue circle of radius 200 meters to our map. The circular marker will look like the image below:
Popups are useful for attracting user attention, encouraging specific user action and displaying information when a user hovers over or clicks certain features on the map.
In Leaflet, you can use the bindPopup
method to attach popups to objects. The bindPopup
method attaches a popup with the specified HTML to a marker:
const restrictedArea = L.circle([50.5, 7.5], { color: "red", fillColor: "red", fillOpacity: 0.5, radius: 600, }).addTo(map); restrictedArea.bindPopup("<b>Restricted area</b>");
The code above will add a red circular marker illustrating a restricted area. It opens a popup when the marker is clicked. The popup will look like the image below:
By default, Leaflet displays the popup after clicking the marker. However, you can also open the popup using the openPopup
function like so:
restrictedArea.bindPopup("<b>Restricted area</b>").openPopup();
In Leaflet, overlays are layers that you can place on top of the base layer. You can use them to display visual elements and highlight specific features without replacing the base map.
Leaflet has three built-in overlay APIs:
ImageOverlay
VideoOverlay
SGVOverlay
After creating a map, you can use the L.ImageOverlay
method to load and display a single image within specific bounds of the map:
const imageUrl = "historical-map.png"; const latLngBounds = L.latLngBounds([ [50.4, 7.4], [50.6, 7.6], ]); const imageOverlay = L.imageOverlay(imageUrl, latLngBounds, { opacity: 0.8, alt: "This is alt text for the image", interactive: true, }).addTo(map);
As illustrated above, the L.imageOverlay
method takes the image URL, the bounds within which to display the image and an optional object as arguments. The code above will load the image within the provided bounds.
Similarly, you can use the L.VideoOverlay
function to add video overlay to your base map.
As explained above, Leaflet was intentionally designed to be minimal and lightweight. It bundles only the core mapping features you need. However, you can extend its built-in features using plugins.
Leaflet has a whole ecosystem of plugins. Each plugin has its own documentation. For example, the ResetView
plugin adds reset view control to your map. You can load it from a CDN and use it like so:
L.control .resetView({ position: "topleft", title: "Reset view", latlng: L.latLng([51.505, -0.09]), zoom: 13, }) .addTo(map);
You can also create your own plugin if those in the ecosystem do not meet your project requirements. The Leaflet documentation has detailed guides on how to create plugins.
In this section, we will explore some of the common use cases of Leaflet. There are many, but some popular ones include:
Leaflet is a popular, open source mapping library. However, it’s by no means the only mapping library in the JavaScript ecosystem. In this section, we will compare Leaflet with OpenLayers, Mapbox GL JS, Google JavaScript API, and ArcGIS API for JavaScript.
OpenLayers is a feature-rich, free, open source mapping library for creating interactive maps for the web. It is very similar to Leaflet in many ways:
Leaflet is more widely used and has a larger community in comparison to OpenLayers. If that’s an important factor to you — for example, since a larger community could translate to more peer resources and faster answers to your questions — then Leaflet might be the better choice.
Mapbox GL JS is a JavaScript mapping library developed by Mapbox. You can use it to create interactive maps in a web application. These libraries share some similarities, but have some important differences as well:
Understanding these differences might help you determine which library is better suited to your project requirements.
The Google Maps JavaScript API is another JavaScript package you can use to create interactive maps in your web and mobile application. Though you primarily use Google maps as the base map with the Google maps JavaScript API, it also gives you the flexibility to create maps with custom map imagery.
Here are some important points to consider when comparing the two:
If you’re willing to pay for the extensive feature set offered by the Google Maps JavaScript API, it could be a more convenient option, especially considering that it’s developed and maintained by Google itself.
However, keep in mind that Leaflet is highly extensible and performant, which allows it to meet most needs without the cost associated with the Google Maps JavaScript API — although its free tier is fairly generous.
The ArcGIS Maps SDK for JavaScript is a proprietary software development kit for building interactive maps. It is developed and maintained by Esri. It has built-in features for 2D and 3D visualization. In this sub-section, we will compare Leaflet and ArcGIS map SDK for JavaScript:
If your project specifically requires 3D maps, the ArcGIS Maps SDK for JavaScript is your best bet.
Some of the above comparisons have been summarized in the table below:
Leaflet | OpenLayers | Mapbox GL JS | Google Maps JavaScript API | ArcGIS Maps SDK for JavaScript | |
---|---|---|---|---|---|
License | BSD 2 clause | BSD 2 clause | Mapbox Terms of Service | Google Maps Platform Terms of Service | ArcGIS Maps SDK for JavaScript Terms of Service |
GitHub stars | 40.7k | 11.2k | 11k | Not available | Not available |
Open source | Yes | Yes | No | No | No |
Active maintenance | Yes | Yes | Yes | Yes | Yes |
Documentation | Good | Good | Good | Good | Good |
Pricing | Free | Free | Paid service with a generous free tier | Paid service with a generous free tier | Paid service with a generous free tier |
Community support | Good | Good | Good | Good | Good |
Ease of use | Easy | Easy | Easy | Easy | Easy |
npm weekly downloads | 1,028,448 | 205,627 | 953,407 | Not available | Not available |
Leaflet is a handy JavaScript library for creating responsive and interactive maps for the web. It was intentionally designed to be minimal. By default, it ships the core mapping features that you will almost always use in your app. Therefore, Leaflet is a lightweight and performant library.
You can extend the built-in features using plugins. It has an extensive collection of plugins in its ecosystem. If the feature you need doesn’t have a third-party plugin, you can also create your own.
Leaflet is just a library. It doesn’t provide mapping data. You need to source map imagery from third party providers like OpenStreetMap. Therefore, be sure your third-party tile provider has taken appropriate measures to avoid compromising your application’s security.
There’s no doubt that frontends are getting more complex. As you add new JavaScript libraries and other dependencies to your app, you’ll need more visibility to ensure your users don’t run into unknown issues.
LogRocket is a frontend application monitoring solution that lets you replay JavaScript errors as if they happened in your own browser so you can react to bugs more effectively.
LogRocket works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.
Build confidently — start monitoring for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowThe useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.
Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.
Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.
Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]