I'm trying to set up a new angular v18 app with a leaflet map integration but while I'm configuring leaflet settings almost exactly to how I set them up in a working angular 17 app, the map just doesn't want to display correctly. It is a very minimal setup for the time being but the difficulties in getting the map to display have been somewhat of a bottleneck... Could anyone help?
app config ts:
import {
ApplicationConfig,
provideExperimentalZonelessChangeDetection,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
export const appConfig: ApplicationConfig = {
providers: [
provideExperimentalZonelessChangeDetection(),
provideRouter(routes),
provideAnimationsAsync(),
],
};
map component ts:
import {
Component,
inject,
AfterViewInit,
ViewChild,
ElementRef,
OnInit,
} from '@angular/core';
import { MapService } from '../map.service';
import { MaterialModule } from '../../wcm-modules/material/material.module';
@Component({
selector: 'app-map-layer',
standalone: true,
imports: [MaterialModule],
template: ` <div id="map-container">
<div id="map"></div>
</div>`,
styles: `
.map-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#map {
height: 100%;
width: 100%;
position: relative;}
`,
})
export class MapLayerComponent implements OnInit, AfterViewInit {
constructor(private mapService: MapService) {}
ngOnInit(): void {
console.log('MapLayerComponent initialized!');
}
ngAfterViewInit(): void {
console.log('Attempting to create map!');
this.mapService.createMap('map');
}
}
map service ts:
import { Injectable } from '@angular/core';
import * as L from 'leaflet';
@Injectable({
providedIn: 'root',
})
export class MapService {
public map!: L.Map;
// Function to create a map
public createMap(mapId: string): any {
console.log('Map Sercive create map function started!');
this.map = L.map(mapId).setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
}).addTo(this.map);
}
}
I couldn't reproduce your exact example (as I don't have MaterialModule
) but I think the problem is your CSS selector in map.component.ts
.
map-container
is not a class but an ID, use:
#map-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}