Leaflet

1.9.4 · maintenance · verified Sun Apr 19

Leaflet is a lightweight, open-source JavaScript library designed for creating mobile-friendly interactive maps. It focuses on performance, usability, and extensibility, providing a core set of features like layers, markers, popups, and controls, while supporting a rich ecosystem of plugins for advanced functionality. The current stable major version is 1.x, with `1.9.4` being the latest bugfix release, which is now in maintenance mode, receiving only critical bugfixes. Development has shifted significantly towards the upcoming 2.0 release, currently in alpha, which modernizes the codebase by dropping Internet Explorer support, removing legacy methods, and fully embracing ES Modules. Its simple API and strong community support make it a popular choice for web mapping applications, particularly where performance and bundle size are critical.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a basic Leaflet map, add an OpenStreetMap tile layer, and place a marker with a popup. It also addresses the common issue of missing marker icons when using bundlers.

import 'leaflet/dist/leaflet.css'; // Essential for Leaflet styles

// For TypeScript with bundlers and Leaflet 1.x, `import * as L from 'leaflet';` is common.
// For native browser usage with script tags, `L` is globally available.
import * as L from 'leaflet';

// A common issue in bundlers is that Leaflet's default marker icons aren't correctly resolved.
// We override L.Icon.Default to point to known URLs, preventing missing marker images.
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
  iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
  shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png'
});

document.addEventListener('DOMContentLoaded', () => {
  // Ensure a map div exists
  let mapDiv = document.getElementById('map');
  if (!mapDiv) {
    mapDiv = document.createElement('div');
    mapDiv.id = 'map';
    mapDiv.style.height = '400px';
    mapDiv.style.width = '100%';
    document.body.appendChild(mapDiv);
  }

  // Initialize the map on the 'map' div with a given view and zoom level
  const map = L.map('map').setView([51.505, -0.09], 13);

  // Add an OpenStreetMap tile layer to the map
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  // Add a marker to the map at a specific coordinate
  L.marker([51.5, -0.09])
    .addTo(map)
    .bindPopup('A sample marker in London!')
    .openPopup();
});

view raw JSON →