I’m a recent angular user.
I’m trying to add a leaflet map to my project.
I saw that I had to use a service to avoid errors related to window.
I used the following example: https://github.com/NickToony/universal-starter-leaflet-example
I made my map.service.tst file like this
import { Injectable, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Injectable()
export class MapService {
public L = null;
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
if (isPlatformBrowser(platformId)) {
this.L = require('leaflet');
}
}
}
and my map.component.ts file like this
import { Component, OnInit } from '@angular/core';
import { MapService } from '../services/map.service';
import { Map } from 'leaflet';
@Component({
selector: 'app-map',
standalone: true,
imports: [],
templateUrl: './map.component.html',
styleUrl: './map.component.css',
})
export class MapComponent implements OnInit {
public message!: string;
private map!: Map;
constructor(private mapService: MapService) {}
ngOnInit() {
if (this.mapService.L) {
// Leaflet is loaded - load the map!
this.message = 'Map Loaded';
this.setupMap();
} else {
// When the server renders it, it'll show this.
this.message = 'Map not loaded';
}
}
private setupMap() {
if (!this.mapService || !this.mapService.L) {
console.error('mapService is not initialized');
return;
}
// Create the map in the #map container
this.map = this.mapService.L.map('map').setView([51.505, -0.09], 13);
// Add a tilelayer
this.mapService.L.tileLayer(
'http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png',
{
attribution:
'copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>,' +
' Tiles courtesy of <a href="http://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>'
}
).addTo(this.map);
}
}
in map.component.ts, I have two errors
The ‘map’ property doesn’t exist on the ‘never’ type.
The ’tileLayer’ property doesn’t exist on the ‘never’ type.
I can’t figure out how to get past these two errors.
jean-marie carré is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.