Interactive maps are no longer reserved for large GIS teams or expensive enterprise software. With Leaflet.js, you can add fast, flexible, and mobile-friendly maps to a website using just a little JavaScript. Whether you are building a store locator, a travel guide, a delivery dashboard, or a city data visualization, Leaflet gives you the tools to turn location data into something users can explore.
TLDR: Leaflet.js is a lightweight JavaScript library for creating interactive web maps with markers, popups, layers, and custom controls. For example, a café chain with 12 locations could use Leaflet to show nearby branches, opening hours, and walking directions in a simple embedded map. In many content-driven websites, interactive maps can increase engagement because users spend more time exploring location-based information. If you know basic HTML, CSS, and JavaScript, you can build a useful Leaflet map in under 30 minutes.
Table of Contents
What Is Leaflet.js?
Leaflet.js is an open-source JavaScript library designed for building interactive maps. It is known for being small, fast, and easy to learn. Unlike full GIS platforms, Leaflet focuses on the essentials: displaying map tiles, adding markers, drawing shapes, handling user interactions, and supporting plugins.
Leaflet works with tile providers such as OpenStreetMap, Mapbox, Stadia Maps, and others. It does not own the map imagery itself; instead, it gives you the interface for displaying and controlling map layers.
Image not found in postmetaWhy Use Leaflet?
Leaflet has become popular because it balances simplicity with power. You can start with a basic map in a few lines of code, then expand it with custom icons, GeoJSON overlays, clustering, heatmaps, and routing.
- Lightweight: Leaflet’s core library is small, which helps pages load quickly.
- Mobile friendly: It supports touch gestures, pinch zooming, and responsive layouts.
- Open source: It is free to use and supported by a large developer community.
- Plugin ecosystem: You can add advanced features without building everything from scratch.
- Beginner friendly: The API is readable and easy to understand.
Setting Up Your First Leaflet Map
To begin, you need to include Leaflet’s CSS and JavaScript files in your page. Then create a container where the map will appear.
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css">
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<div id="map" style="height: 400px;"></div>
Next, initialize the map with JavaScript. The following example centers the map on London and sets the zoom level to 13:
const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
The first number in the coordinate pair is latitude, and the second is longitude. The zoom level controls how close the map appears. A value around 2 shows continents, while 13 or 14 shows streets and buildings.
Adding Markers and Popups
Markers are one of the most common Leaflet features. They help users identify specific locations such as shops, hotels, offices, attractions, or delivery points.
const marker = L.marker([51.505, -0.09]).addTo(map);
marker.bindPopup('<strong>Hello from London!</strong><br>This is a Leaflet marker.');
A popup can contain text, HTML, images, buttons, or links. For example, a restaurant website might show the restaurant name, today’s hours, and a “Book a Table” button inside the popup.
Using Custom Icons
Default markers are useful, but custom icons can make your map clearer and more polished. Imagine a tourism map where museums, parks, restaurants, and train stations each have different symbols.
const cafeIcon = L.icon({
iconUrl: 'cafe-icon.png',
iconSize: [32, 32],
iconAnchor: [16, 32],
popupAnchor: [0, -32]
});
L.marker([51.51, -0.1], { icon: cafeIcon })
.addTo(map)
.bindPopup('Central Café');
The iconAnchor option tells Leaflet which point of the icon should touch the map coordinate. This is especially important when using pin-shaped icons.
Drawing Circles, Lines, and Polygons
Leaflet can also draw shapes directly on the map. This is helpful when you want to highlight service areas, routes, boundaries, event zones, or construction regions.
L.circle([51.508, -0.11], {
color: 'blue',
fillColor: '#3388ff',
fillOpacity: 0.3,
radius: 500
}).addTo(map).bindPopup('500 meter service area');
You can draw a route with a polyline:
const route = [
[51.505, -0.09],
[51.51, -0.1],
[51.515, -0.12]
];
L.polyline(route, {
color: 'red',
weight: 4
}).addTo(map);
Polygons work similarly and are perfect for showing neighborhoods, delivery zones, school districts, or protected natural areas.
Working With GeoJSON
GeoJSON is a popular format for storing geographic data. It can represent points, lines, polygons, and related properties. Leaflet has built-in support for GeoJSON, making it easy to load structured location data.
const geojsonData = {
"type": "Feature",
"properties": {
"name": "Sample Park"
},
"geometry": {
"type": "Point",
"coordinates": [-0.09, 51.505]
}
};
L.geoJSON(geojsonData, {
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.name);
}
}).addTo(map);
Notice that GeoJSON coordinates are written as longitude first, latitude second. This is the opposite of Leaflet’s usual [latitude, longitude] format, so it is a common beginner mistake.
Practical Example: Store Locator Map
Let’s build a simple store locator. Suppose a small retailer has three branches and wants users to click each marker for details.
const stores = [
{
name: 'North Branch',
coords: [51.52, -0.08],
hours: '9:00 AM - 6:00 PM'
},
{
name: 'Central Branch',
coords: [51.505, -0.09],
hours: '8:00 AM - 8:00 PM'
},
{
name: 'South Branch',
coords: [51.49, -0.1],
hours: '10:00 AM - 5:00 PM'
}
];
stores.forEach(store => {
L.marker(store.coords)
.addTo(map)
.bindPopup(
'<strong>' + store.name + '</strong><br>' +
'Hours: ' + store.hours
);
});
This basic pattern can scale quickly. You could add phone numbers, product availability, distance from the user, or filters for store services such as parking, pickup, or wheelchair access.
Adding User Location
Leaflet can request the user’s location through the browser’s geolocation API. This is useful for finding nearby stores, showing local events, or centering the map on a delivery address.
map.locate({ setView: true, maxZoom: 14 });
map.on('locationfound', function(e) {
L.marker(e.latlng)
.addTo(map)
.bindPopup('You are here')
.openPopup();
L.circle(e.latlng, e.accuracy).addTo(map);
});
map.on('locationerror', function() {
alert('Location access was denied or unavailable.');
});
Always explain why you are asking for location access. Users are more likely to allow it when the benefit is clear, such as “Show stores near me” or “Find events in my area.”
Image not found in postmetaUseful Leaflet Plugins
Leaflet’s plugin ecosystem is one of its biggest advantages. Instead of writing advanced map behavior from scratch, you can use existing extensions.
- MarkerCluster: Groups many nearby markers into clusters for cleaner maps.
- Leaflet Draw: Lets users draw shapes directly on the map.
- Leaflet Routing Machine: Adds route planning and turn-by-turn paths.
- Heatmap plugins: Display density patterns, such as traffic, sales, or reports.
- Fullscreen controls: Allow users to expand the map for easier exploration.
Best Practices for Leaflet Maps
To make your maps useful and reliable, keep the user experience in mind. A map should not just look good; it should help people make decisions quickly.
- Keep markers meaningful: Too many markers without filtering can overwhelm users.
- Use clustering for large datasets: Hundreds of markers can slow performance and create visual clutter.
- Choose readable colors: Lines and polygons should stand out against the base map.
- Optimize for mobile: Make sure the map container has a clear height and touch controls work smoothly.
- Respect attribution: Tile providers usually require visible credit on the map.
Final Thoughts
Leaflet.js is an excellent choice for developers who want to build interactive maps without unnecessary complexity. It is approachable enough for beginners, yet flexible enough for serious applications involving GeoJSON, custom layers, user location, and plugins. Start with a simple marker map, then gradually add features that solve real user problems. The best Leaflet maps are not the most complicated ones; they are the ones that make location-based information clear, useful, and enjoyable to explore.


