How to use Leaflet with NPM

How to use Leaflet with NPM: this tutorial shows how to install Leaflet from NPM and create a map and display it on a web page.

You can pick from a large selection of bundlers and always find the best solution for your project. Whether you prefer Parcel, Webpack, Rollup, Turbopack, or anything else.

  1. Install the npm package.
  1. Create the map style. Add the map style to your stylesheet. The div must have non-zero height.

body { 
  margin: 0;
  padding: 0;
}

#map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
}
  1. Create a <div> element with a certain id where you want your map to be.

    Add <div> tag into your page. This div will be the container where the map will be loaded.

  2. Include the CSS file.

    If you have a bundler that can handle CSS, you can import the CSS from leaflet/dist/leaflet.css.

    Note

    Including the CSS file using a <link> in the head of the document via the CDN is the easiest way.

    
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    
  3. Finally, load the map with the style. Include the following code in your JavaScript.


import L from "leaflet";

import 'leaflet/dist/leaflet.css';

const map = L.map('map', {
  center: L.latLng(49.2125578, 16.62662018),
  zoom: 14,
});

const key = 'YOUR_MAPTILER_API_KEY_HERE';

L.tileLayer(`https://api.maptiler.com/maps/streets-v4/{z}/{x}/{y}.png?key=${key}`,{ //style URL
  tileSize: 512,
  zoomOffset: -1,
  minZoom: 1,
  attribution: "\u003ca href=\"https://www.maptiler.com/copyright/\" target=\"_blank\"\u003e\u0026copy; MapTiler\u003c/a\u003e \u003ca href=\"https://www.openstreetmap.org/copyright\" target=\"_blank\"\u003e\u0026copy; OpenStreetMap contributors\u003c/a\u003e",
  crossOrigin: true
}).addTo(map);
  1. Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.

Learn more

Check out the tutorial How to create a map with Leaflet, NPM and Parcel.

How to use Leaflet with React and Vector Tiles.

Leaflet with React

Tutorials

Integrate Leaflet and MapTiler Vector Tiles in React applications.

How to use Leaflet with TypeScript

Leaflet with TypeScript

Tutorials

Install Leaflet via NPM to display maps in TypeScript apps.

How to use Leaflet with Next.js and Vector Tiles.

Leaflet with Next.js

Tutorials

Integrate Leaflet and MapTiler Vector Tiles in Next.js applications.

How to use Leaflet with Vite and MapTiler Vector Tiles in vanilla JS

Leaflet with Vite (vanilla JS)

Tutorials

Integrate Leaflet and MapTiler Vector Tiles in Vite vanilla JS.

Was this helpful?