Getting Started with Leaflet in Angular

Ole Ersoy
Jan 11, 2023
Image by annca from Pixabay

Scenario

We want a basic starting point for creating Leaflet demoes with Angular.

Approach

Install

First add the dependencies:

  • leaflet
  • @asymmetrik/ngx-leaflet
  • @types/leaflet

Within app.component.ts import leaflet .


import * as L from 'leaflet';

Styling

Add the leaflet style sheet to the head of index.html .

<link
rel="stylesheet"
type="text/css"
href="./node_modules/leaflet/dist/leaflet.css"
/>

Configuration

Create a basic leaflet configuration object.

  options: any = {
zoomControl: false,
layers: [
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 4,
attribution: '...',
}),
],
zoom: 2,
center: L.latLng({ lat: 38.991709, lng: -76.886109 }),
};

Note that we switched off zoomControl and we will add it back in our mapReady method.

  mapReady(map: L.Map) {
map.addControl(L.control.zoom({ position: 'bottomright' }));

// Reset the map
setTimeout(() => {
map.invalidateSize();
}, 0);
}

View

With app.component.html declare a leaflet element.

<div
style="height: 300px;"
leaflet
[leafletOptions]="options"
(leafletMapReady)="mapReady($event)"
></div>

Demo

--

--