TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox.

Below is the Angular TypeScript code I am working with:

export class MappViewComponent implements OnInit {
  map: mapboxgl.Map;
  lat = 41.1293;
  lng = -8.4464;
  style = "mapbox://styles/mapbox/streets-v11";
  zoom = 8;

  constructor(
    private mapService: MapService,
    private nodeService: NodeService
  ) {}

  ngOnInit() {
    this.buildMap(this.map);
    /*var mymap = L.map('mapID').setView([41.260555, -8.436098], 10);
    this.buildMap(mymap);*/
    this.addMarkersLines(this.map);
    new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map);
  }

  /**https://leafletjs.com/reference-1.7.1.html */
  buildMap(map: any) {
    map = new mapboxgl.Map({
      accessToken:
        "accessToken",
      container: "mapID",
      style: this.style,
      zoom: this.zoom,
      center: [this.lng, this.lat],
      antialias: true,
      attributionControl: false,
    });
    map.addControl(new mapboxgl.NavigationControl());

The issue arises when running the code in console and encountering an error on this line:

new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map); 

Error message: TypeError: t is undefined addTo mapbox-gl.js:35 ngOnInit mapp-view.component.ts:30

Has anyone else faced a similar problem?

Answer №1

It is very likely that the error is happening because this.map is currently undefined in this scenario:

new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map);
                                                            ^^^^^^^^  
                                                            undefined 

The way the buildMap function is written, it does not change the object being passed in, which results in this.map remaining undefined. You may want to update the implementation of the buildMap function like so:

buildMap() {
    this.map = new mapboxgl.Map({
      accessToken: MAPBOX_TOKEN,
      container: 'mapID',
      style: this.style,
      zoom: this.zoom,
      center: [this.lng, this.lat],
      antialias: true,
      attributionControl: false,
    });
    this.map.addControl(new mapboxgl.NavigationControl());
 }

Usage

ngOnInit() {
    this.buildMap();
    new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map);
}

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

Is AngularJS treating variables as text in their dynamic template directives?

Need help modifying this Angular component: (more details here: https://github.com/khan4019/tree-grid-directive) The issue at hand is simple. The tree-grid component does not allow formatting of specific columns using filters. For example, I want to conv ...

Using regular expressions to identify the presence of "&", parentheses, and consecutive letters in a string

I specialize in working with JavaScript and I have a need to verify if my text contains certain characters. Specifically, I want to check for the presence of parentheses (), ampersands (&), and repeating letters within the text. Here are some examples: te ...

Utilizing a method to nest schemas within schemas thanks to Mongoose

I am currently working on developing a blog that utilizes Node.js as the server-side language and integrates with Mongo DB. Within my blog, users will have the ability to create posts and interact through commenting, just like any typical blog platform. ...

Identify and alert when the download has finished

Imagine having a drive link to download a zip file. Upon clicking the link, the download begins in the browser. After the download finishes, I would like to send an email notification to the user. Is this achievable? I am using a .NET application (C#) wi ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

Having trouble viewing the image slider on an HTML webpage

I've been attempting to incorporate an image slider into my personal website on GitHub, but I've encountered some difficulties as the images are not displaying. Interestingly, I can load individual images without using the slider and they show up ...

Leveraging the @Input decorator to send external data into the Angular component

In my Ionic app, I am utilizing an Angular component. Within this component, there is a variable called headerText that is supposed to be initialized from the page where the component is being used. The issue arises when the headerText variable is always ...

Exploring Typescript: Combining types (rather than intersecting them)

Let's analyze the scenario below type MergeFn = <K1 extends string, V1, K2 extends string, V2>( k1: K1, v1: V1, k2: K2, v2: V2 ) => ??? let mergeFn: MergeFn // actual implementation doesn't matter for this question What should b ...

Initially, the 'display none' CSS command may not take effect the first time it is used

I am currently working on a slideshow application using jquery.transit. My goal is to hide a photo after its display animation by setting the properties of display, transform, and translate to 'none' value. Although the slideshow application work ...

What is the best location to include my JavaScript code in WordPress?

Alright, so I've got this world map on one of my WordPress pages and here's an example of the code: <area onmousedown="modifyImage('world_map_01', './images/map/asia.jpg')" onmouseout="modifyImage('world_map_01', ...

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

Issue with calling hooks. Hooks can only be invoked within the body of a function component

Looking to develop a todo application using React, but encountering an issue with the useContext hook. The error message "Invalid hook call..." suggests a few possible reasons for this problem: Possible mismatched versions of React and the renderer (e.g ...

Enlarge the div with a click

I was looking for a solution on how to make a div expand when clicked using jQuery I came across a tutorial that seemed simple and perfect, but I couldn't get it to work when I tried to replicate the code. Do you know if this code is still valid wit ...

Encountering MIME type error (text/html) during Angular project deployment

I am facing an issue while trying to deploy a project built with Angular/CLI 6.12.0. After transferring the content of the "dist" folder to a server, I encountered a console error related to MIME type. The module at address "http://www.sylvainallain.fr/p ...

Displaying a component upon clicking a button in Angular 9

Within the navbar, there is a "+" button that triggers the display of the component. <app-navbar></app-navbar> Upon clicking the button, the <app-stepper></app-stepper> component should be shown. <app-navbar></app-navba ...

Tips for adding a console.log statement to material-ui components to confirm the object/array/value

An issue arises in my React JS code snippet execution that I need help with: <TableBody> { (data.length > 0) ? ( data.map((x, i) => row( x, i, formColumns, handleRemove, handleSelect, editIdx ))) : (<TableRo ...

Having trouble monitoring button clicks with Jest and React Testing Library while testing a component scenario

Hey there, I'm new to React testing library and I've been struggling with writing a test case that isn't giving me the results I expected. I could really use some guidance. When I run npm run test, it shows the expected number of calls >= ...

Monitoring user engagement using Socket.io and Firebase

In my Node/Express app, I am working on monitoring active users without using sessions. The app relies on an external API for handling JWT tokens that are directly passed to the client for storing and subsequent API requests. To track active users, I am u ...

The echo statement is failing to show any value following the ajax request

I am in need of assistance. I would like to output the value from a PHP echo statement using an AJAX call. Currently, the code is functioning without any errors. When I select options from a dropdown menu, the value is displayed on the console by using con ...