Search code examples
angularmapbox-gl

TypeError: Cannot read property 'map' of undefined at .addTo(this.map)


I am using mapbox in my angular application. I am trying to place markers on the map. I followed the mapbox example and changed it to angular

geojson.features.forEach(function (marker) {

      //   // create a HTML element for each feature
      var el = document.createElement('div');
      if (marker.properties.on_ground == true)
        el.className = 'marker-on_ground';
      else
        el.className = 'marker-air';

      // make a marker for each feature and add to the map
      new mapboxgl.Marker(el)
        .setLngLat(marker.geometry.coordinates)
        .addTo(this.map);

    });

But when I save this I am getting an error TypeError: Cannot read property 'map' of undefined at .addTo(this.map)


Solution

  • I solved this error by using Arrow function as suggested by @Ashish Rajan. I changed my code as fallow

    geojson.features.forEach((marker) => {
    
      //   // create a HTML element for each feature
      var el = document.createElement('div');
      if (marker.properties.on_ground == true)
        el.className = 'marker-on_ground';
      else
        el.className = 'marker-air';
    
      // make a marker for each feature and add to the map
      new mapboxgl.Marker(el)
        .setLngLat(marker.geometry.coordinates)
        .addTo(this.map);
    
    });