OpenStreetMap in Angular

If you are here, you probably need to embed a map in your Angular application. The most common option is Google Maps, but it is not always the best one for side projects or applications with a limited budget.

npm install --save @ types/googlemaps

Its free tier is limited and billing setup is more restrictive than many teams expect. For that reason, I recommend using Leaflet together with OpenStreetMap.

Leaflet is a lightweight library for interactive maps, and OpenStreetMap provides open geographic data. Below you can see a working example.

Why Leaflet works well in Angular

Leaflet keeps the map layer light, avoids a mandatory billing account and works well with OpenStreetMap tiles. In Angular Universal projects the key detail is loading the browser-only map code after SSR has delivered the article content, so Google can index the tutorial even if the interactive map is initialized on the client.

After this base setup, the natural continuation is the article about multilayer Angular maps with WMS overlays and geolocation.

Installation

The first step is installing the required libraries:

Then add the following configuration to angular.json:

Once installed, create a component with the following template:

Example file: component.scss

.map-container {
  width: 100%;
  margin: 1.5rem 0;
}

.map-frame {
  border: 2px solid black;
  min-height: 610px;
  overflow: hidden;
}

#map {
  height: 610px;
  width: 100%;
}

Example file: component.ts

You can download the code from this repository: https://github.com/al118345/OpenStreetMapAngular12 and watch this video: https://www.youtube.com/watch?v=2zYe5fSa2ZU:

Installation in Angular Universal

In Angular Universal the goal is to support server-side rendering so search engines can index the page correctly and SEO can improve. (https://1938.com.es/app-seo-angular)

In that scenario, the setup changes slightly and you need to move Leaflet loading to the browser side only.

Importante Important: this assumes the base project setup is already completed.

LeafletService

Create a new service so the browser loads the mapping libraries only when the code runs client-side.

Command

File: service/leaflet.service.ts

Then update the component.ts with the following code:

Remove these imports:

Add the service import:

And update tsconfig.app.json with this configuration:

You can download the Angular Universal version here: https://github.com/al118345/OpenStreetMap_Angular13_Universal

If you want to continue, the next article covers user geolocation and multilayer maps: https://1938.com.es/ejemplo-maps-multicapa.