Setting mapboxgl.accessToken in an Angular project - a step-by-step guide

Can anyone help me figure out how to set the accessToken for mapbox-gl in an example on StackBlitz?

After attempting to do so, I received an error message stating "Cannot assign to 'accessToken' because it is a constant or a read-only property".

I've already tried some solutions suggested in 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
    });
  }
}

For the complete code example, check out: https://stackblitz.com/edit/angular-9djiw2

Answer №1

One useful tip is to set the token property by using this code snippet:

(mapboxgl as any).accessToken = "your access token"

Answer №2

Resolved the issue at hand by switching

import * as mapboxgl from 'mapbox-gl';

to

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

The reason behind this solution is unclear (despite seeing some red underlines). It might be related to StackBlitz specifically. I will keep the example intact, but will deactivate the key from Mapbox.

Answer №3

When working with typescript, I wanted to continue using the import feature. After some trial and error, I found a solution that worked for me:

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

To create an instance of the map, I used the following code:

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]
})

For those who want to see a complete example, here is how you would do it in HTML:

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

If there are any improvements or corrections needed, please let me know.

Answer №4

Try implementing something similar effective for 2023

Include it during the initialization process.

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
    });
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind angular 4.3's httpclient returning Object instead of any?

The Angular 4.3 update introduces the new HttpClient class, which appears to return Object instead of any as the default type. Is there a specific reason for this decision, especially considering the TypeScript documentation advises against using types li ...

Error: An unexpected closing tag "<p>" was encountered while parsing the template

I am facing an issue while trying to format an XML file in Angular. Here is the code snippet I attempted to use: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Raw Request</b> <pre& ...

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

UIManager is not recognized within this context

I'm currently working on a project where I've created a class called UIManager to manage UI changes... /// <reference path="../../typings/jquery/jquery.d.ts" /> /// <reference path="../../typings/materialize-css/materialize-css.d ...

Filtering data from a list of objects in Angular when clicked

0: {user_id: 1, status: Active, account_request_status: 2, first_name: null, last_name: null, email: null,…} 1: {user_id: 3, status: Inactive, account_request_status: 0, first_name: null, last_name: null, email: null,…} 2: {user_id: 37, status: Rejecte ...

Encountering errors in Angular when trying to access a property that is undefined using

One of the components I've created is being used in its parent component: <app-event-menu-nav [event]="event"></app-event-menu-nav> Below is the code for this component: import {Component, OnInit, ChangeDetectionStrategy, Input} ...

Unleash the power of Vue2 with composition API for creating dynamic template refs

Currently, I am utilizing Quasar (quasar.dev) in conjunction with Vue2 + Composition API and attempting to access DOM elements that have dynamically generated 'v-bind:ref' properties. This approach is based on the information provided in this sec ...

The requested resource does not have an 'Access-Control-Allow-Origin' header

- ISSUE: The XMLHttpRequest to 'https://*.execute-api.*.amazonaws.com/api' from 'http://localhost:4200' is blocked by CORS policy. The preflight request doesn't have the necessary 'Access-Control-Allow-Origin' header. ...

Using SystemJS to Import External JavaScript Library into Angular 2

Issue with mapping fileSaver, while angular2-jwt is functioning properly. Performed npm install file-saver -save to obtain file-saver and then referenced it accordingly (confirmed file presence in libs directory via gulp task) In index.html, script inclu ...

Implementing the rendering of HTML stored in an array in Angular

I have an array that includes an object with HTML elements which I would like to render in Angular. Here is the array: { name: "rules", key: "rules", value_before: "<tr><td>revisit_in_some_days</td><td>less_then</td>td> ...

Tips for showcasing both PDF and image files in a single Angular4 component

Recently, I ventured into the world of angular4 and encountered an issue while attempting to showcase both a pdf file and an image file within a component. The problem I faced is as follows: Whenever I select an image, it displays correctly. However, whe ...

Guide on setting up redux store from server component using next.js and app router

I'm currently working with Next.js 13, React, and Redux to handle state management. My main objective is to fetch initial data on the server side and present it on the client side. Although I assumed this would be a typical approach with Redux and Ne ...

Angular Alert: The element 'app-header' is unrecognized in Angular 9

After updating my Angular application from version 5 to version 9, I encountered an error when trying to run it. The error can be seen in the following link: Error Screenshot Below are the details of my code: app.module.ts import { AppComponent } from &a ...

Custom fields provided by Express are not accessible within routes

In my customExpress.d.ts file, I have defined an extended type: declare namespace Express { export interface Request { user: { id: string; }; } } I have also configured it in the tsconfig.json file: ... "typeRoots": ["sr ...

Guiding you on exporting a Typescript class with parameters in Node.js

Trying to find the Typescript equivalent of require('mytypescriptfile')(optionsObject); This is the TS code provided: export class Animal { name: string; public bark(): string { return "bark " + this.name; } constructor(color:string) ...

When using Vue 3 in my app, I discovered that all the TypeScript files are easily accessible through the browser console

I recently completed my Vue3 js app with Typescript, and I have noticed that all the Typescript files are easily accessible for anyone to view through the Sources tab of the browser console. The code is perfectly clear and readable. Is there a method to p ...

What is the reason behind having to coerce the enum value before the object type can be properly recognized?

My object is discriminated based on the type property, which can be any value from a specified enum. I encounter an issue in TypeScript when passing a valid object to a function; it complains about mismatched types. However, coercing the enum value resolve ...

Encountering issue with ngIf directive in Angular

In my Angular project, I am trying to display data from a variable that is formatted in json. I have successfully done this using *ngfor, but now I also want to add a condition where it checks if msg.who=="Bot". My current code looks like this: <div cl ...

Store the checked checkbox's value as 1

Is there a way to store the value of a checked checkbox as 1 and an unchecked checkbox as 0 while using boolean in my model? <div class="form-check form-check-inline"> <input name="vat" class="form-check-input" type="checkbox" id="inl ...

What's the process for validating i18n dictionaries using TypeScript?

Is there a way to enforce type checking on existing keys within dictionaries in react-i18next? This means that TypeScript will provide warnings at compile time if a key does not exist. For example: Let's say we have the following dictionary: { "f ...