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.
- Install the npm package.
- Install the Leaflet types package.
- 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%;
}
-
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. -
Include the CSS file.
If you have a bundler that can handle CSS, you can import the CSS from leaflet/dist/leaflet.css.
-
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);
- Replace
YOUR_MAPTILER_API_KEY_HEREwith your own API key. Make sure to protect the key before you publish it!
Learn more
Check out the tutorial How to create a map with Leaflet, TypeScript and Parcel.
-
Install bundler and build tools. This tutorial will use Parcel because it works out of the box without any additional configuration.
-
Update the package.json scripts. Create the
devandbuildscripts. -
Install the Leaflet npm package.
-
Create a
srcfolder and inside this forder create 3 files:index.html,app.ts, andstyle.css. -
Copy the following code, paste it into
index.htmlfile. The<div id="map">will be the container where the map will be loaded. -
Create the map container style. Add the map container style to you stylesheet
style.css. The div must have non-zero height. In this case we are going to make a fullscreen map. -
Include the following code in your
app.tsfile. -
Replace
YOUR_MAPTILER_API_KEY_HEREwith your own API key. Make sure to protect the key before you publish it! -
Running the dev server. To see the map run the local server. Open a terminal and write.
- Now you can see your application opening http://localhost:1234 in your browser.