I'm trying to load the Mapbox map only once by storing the map object in a Service and reusing it in a custom component.
It's working fine the first time I load the map. The map is correctly added to it's container.
But when I try to use to map object that is already created via the Service, the map is not displayed. My map object is correct (if I console.log() it for example) but it's not added to the container.
Here's the service:
export class MapboxService {
public map: Map | undefined = undefined
constructor(private http: HttpClient) { }
private loadMap(center: [number, number]): void {
this.map = new Map({
container: 'map',
style: 'mapbox://styles/planidays/ckqbcju7w2acp18qtgj9xyegw',
center: center,
zoom: 15,
})
// Add zoom and rotation controls to the map.
this.map.addControl(new NavigationControl())
}
public getMap(center: [number, number]): Map | undefined {
if (!this.map) {
this.loadMap(center)
}
return this.map ? this.map : undefined
}
}
Here's the custom component TS:
export class MapComponent implements OnInit {
center: [number, number] = [-73.974187, 40.771133]
private map: mapboxgl.Map | undefined = undefined
constructor(private mapboxService: MapboxService) {}
ngOnInit(): void {
this.map = this.mapboxService.getMap(this.center)
}
}
Here's the custom component HTML:
<div #map id='map' class="map"></div>
I think that the ref of the container change each time I use the map object thus it's not added to it, but I'm not sure. Any idea ?