6

I'm trying to make an example on StackBlitz with mapbox-gl. How can I set the accessToken?

The editor states "Cannot assign to 'accessToken' because it is a constant or a read-only property".

I already tried the possible solutions from another question: Mapbox-gl typing won't allow accessToken assignment

import { Component, ViewChild, ElementRef } from '@angular/core';
import * as mapboxgl from 'mapbox-gl';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @ViewChild('map') mapElement: ElementRef;
  map: mapboxgl.Map;

  ngOnInit() {
    mapboxgl.accessToken = '<token>';
    this.map = new mapboxgl.Map({
      container: this.mapElement.nativeElement,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [-77.04, 38.907],
      zoom: 11.15
    });
  }
}

Full code example: https://stackblitz.com/edit/angular-9djiw2

Zoe
  • 27,060
  • 21
  • 118
  • 148
Kees Boogert
  • 101
  • 6

4 Answers4

5

Another trick is to access token property as following: (mapboxgl as any).accessToken = "your token"

Ivan Popkov
  • 73
  • 1
  • 3
4

Finally solved this problem by replacing

import * as mapboxgl from 'mapbox-gl';

with

const mapboxgl = require('mapbox-gl');

I don't know why this works (despite some red underlines). It could be specific to StackBlitz. I will leave the example there, but will disable the key from Mapbox.

Kees Boogert
  • 101
  • 6
  • +1, this also worked for me. To get rid of the red underlines, simply install `@types/node` in the dependencies tab! – Lauren May 06 '19 at 14:48
2

I was using typescript and I wanted to keep using import. So finally it works with:

import { Map } from "mapbox-gl/dist/mapbox-gl"
import * as mapboxgl from "mapbox-gl/dist/mapbox-gl"

and then, to create the instance of the map:

mapboxgl.accessToken = "YOUR_API_KEY_BLA_BLA_BLA"
this.map = new Map({
    container: "mapId",
    style: "mapbox://styles/mapbox/light-v9",
    zoom: 5,
    center: [-78.880453, 42.897852]
})

and to show a full example. In html:

<div id="mapId"></div>

If I am doing something wrong please tell me.

J.S.R - Silicornio
  • 1,111
  • 13
  • 16
0

Do something like this works as of 2023

Put it inside while initializing.

import { Component, ViewChild, ElementRef } from '@angular/core';
import * as mapboxgl from 'mapbox-gl';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @ViewChild('map') mapElement: ElementRef;
  map: mapboxgl.Map;

  ngOnInit() {
    this.map = new mapboxgl.Map({
      accessToken: '<token>',
      container: this.mapElement.nativeElement,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [-77.04, 38.907],
      zoom: 11.15
    });
  }
}