Introduction
OpenStreetMap (OSM) is a free, editable map of the world that can be integrated into Angular applications.
One of the most common ways to use OpenStreetMap in Angular is with Leaflet, a lightweight JavaScript library for creating interactive maps.
In this example, we will create an Angular component that displays an OpenStreetMap map, adds a marker, and shows a popup when the marker is selected.
Step 1: Install Leaflet
First, install Leaflet in your Angular project.
Run the following commands from the project directory:
npm install leaflet
npm install --save-dev @types/leaflet
The leaflet package provides the mapping functionality, while @types/leaflet provides TypeScript type definitions.
Step 2: Import Leaflet CSS
Leaflet requires its CSS file for the map and its controls to display correctly.
Add the following import to the global styles.css file:
@import "~leaflet/dist/leaflet.css";
This makes the Leaflet styles available throughout the Angular application.
Step 3: Create the Angular Map Component
Create a component for the map.
For example:
ng generate component osm-map
The component can then be implemented as follows:
import { Component, AfterViewInit } from '@angular/core';
import * as L from 'leaflet';
@Component({
selector: 'app-osm-map',
template: '<div id="map" style="height: 500px;"></div>',
styleUrls: ['./osm-map.component.css']
})
export class OsmMapComponent implements AfterViewInit {
private map!: L.Map;
ngAfterViewInit(): void {
this.initMap();
}
private initMap(): void {
// Initialize the map centered on Kolkata
this.map = L.map('map').setView(
[22.5726, 88.3639],
13
);
// Add OpenStreetMap tile layer
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap contributors'
}
).addTo(this.map);
// Add a marker
L.marker([22.5726, 88.3639])
.addTo(this.map)
.bindPopup('Welcome to Kolkata!')
.openPopup();
}
}
Understanding the Map Initialization
The following code creates the Leaflet map:
this.map = L.map('map').setView(
[22.5726, 88.3639],
13
);
The first parameter, map, refers to the HTML element where the map will be rendered.
The coordinates represent Kolkata:
Latitude: 22.5726
Longitude: 88.3639
The value 13 represents the initial zoom level.
Add the OpenStreetMap Tile Layer
The following code loads map tiles from OpenStreetMap:
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap contributors'
}
).addTo(this.map);

Join the conversation! Your thoughts help the community grow.