How to use Leaflet with TypeScript

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

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. Install the Leaflet types 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 TypeScript.


import { map, latLng, tileLayer, MapOptions } from "leaflet";

import 'leaflet/dist/leaflet.css';

const options: MapOptions = {
  center: latLng(40.731253, -73.996139),
  zoom: 12,
};

const mymap = map('map', options);

const key = "YOUR_MAPTILER_API_KEY_HERE";

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(mymap);
  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, TypeScript 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 NPM

Leaflet with NPM

Tutorials

Install Leaflet via NPM to create and display web maps.

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.

Was this helpful?