如何将mapbox-gl-draw导入Angular 2/4?

时间:2017-08-18 05:12:20

标签: angular mapbox mapbox-gl-js

我正在Angular 2/4应用程序中导入模块,如下所示:

import { MapboxDraw } from '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw';

并在其中一个组件中使用它:

var draw = new MapboxDraw({
   displayControlsDefault: false,
   controls: {
     polygon: true,
     trash: true
   }
});

map.addControl(draw);

但是当我打开页面时出现错误:

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_4__mapbox_mapbox_gl_draw_dist_mapbox_gl_draw__.MapboxDraw is not a constructor

导入mapbox-gl-draw的最佳方法是什么?

2 个答案:

答案 0 :(得分:6)

这是一个适用于我的机器的最小示例应用程序:它基于github上的这个小项目:https://github.com/haoliangyu/ngx-mapboxgl-starter



import { Component } from '@angular/core';
import * as mapboxgl from 'mapbox-gl';
import * as MapboxDraw from 'mapbox-gl-draw';

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

export class AppComponent {
  ngOnInit() {
    mapboxgl.accessToken = 'your Token';
    let map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/light-v9',
      zoom: 5,
      center: [-78.880453, 42.897852]
    });

    let Draw = new MapboxDraw();

    map.addControl(Draw)

    map.on('load', function() {
      // ALL YOUR APPLICATION CODE
    });
  }
}

#map {
  width: 500px;
  height: 500px;
}

<div id='map'></div>
&#13;
&#13;
&#13;

请注意,我使用'mapbox-gl-draw'代替'@mapbox/mapbox-gl-draw'。所以你可能想通过npm install mapbox-gl-draw尝试安装这个软件包。我尝试了后一个,但这对我来说是一个错误。另外,请不要忘记添加所需的mapbox-gl-draw CSS。

答案 1 :(得分:3)

我已安装Second @Test

将css添加到angular-cli.json

npm install @mapbox/mapbox-gl-draw

<强>组件

"../node_modules/@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css",