Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
Angular Mapbox: Load the map only once using a service?

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 ?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!