Mapbox-gl.js map is undefined in angular-cli project on load event

青春壹個敷衍的年華 提交于 2021-01-28 06:52:43

问题


Started an angular-cli project and installed mapbox-gl via npm. Included the mapbox-gl script and styles in the angular-cli.json file. I can get the map to show, but I cannot add a layer on the load event. The map is undefined suddenly? Here is the template html (app.component.html):

<div id="map" style="margin:0; padding:0; position:absolute; top:25px; bottom:0; width:100%;">
</div>

And here is my component code (app.component.ts):

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  @ViewChild("map") map: Map;
  title = 'app';

  ngOnInit() {

    mapboxgl.accessToken = 'blah';   

    this.map = new Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/light-v9',
      zoom: 5,
      center: [-78.880453, 42.897852]
    });

    this.map.on('load', this.onLoad);
  }

  onLoad(){
    console.log("map is loaded, can I still talk to it?");

    this.map.addLayer({
      "id": "points",
      "type": "symbol",
      "source": {
          "type": "geojson",
          "data": {
              "type": "FeatureCollection",
              "features": [{
                  "type": "Feature",
                  "geometry": {
                      "type": "Point",
                      "coordinates": [-77.03238901390978, 38.913188059745586]
                  },
                  "properties": {
                      "title": "Mapbox DC",
                      "icon": "monument"
                  }
              }, {
                  "type": "Feature",
                  "geometry": {
                      "type": "Point",
                      "coordinates": [-122.414, 37.776]
                  },
                  "properties": {
                      "title": "Mapbox SF",
                      "icon": "harbor"
                  }
              }]
          }
      },
      "layout": {
          "icon-image": "{icon}-15",
          "text-field": "{title}",
          "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
          "text-offset": [0, 0.6],
          "text-anchor": "top"
      }
  });

  }

}

Project located at https://github.com/derobiom/mapboxAngularCli


回答1:


Try using either bind method

this.map.on('load', this.onLoad.bind(this));

or local arrow function

this.map.on('load', () => this.onLoad());

or instance arrow function

load = () => {
  ...

This way this will be referenced to component instance



来源:https://stackoverflow.com/questions/46624792/mapbox-gl-js-map-is-undefined-in-angular-cli-project-on-load-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!