Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import mapbox-gl-draw into Angular 2/4?

I am importing the module in my Angular 2/4 app like this:

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

and using it in one of the components like this:

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

map.addControl(draw);

but I am getting an error when I open the page:

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_4__mapbox_mapbox_gl_draw_dist_mapbox_gl_draw__.MapboxDraw is not a constructor

What is the best way to import mapbox-gl-draw?

like image 243
Afeez Aziz Avatar asked Aug 18 '17 05:08

Afeez Aziz


2 Answers

This is a minimal example app that works on my machine: It is based on this little project on 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>

Note that I am using 'mapbox-gl-draw' instead of '@mapbox/mapbox-gl-draw'. So you might wanna try installing this package via npm install mapbox-gl-draw. I tried the later one but this throws an error for me. Also don't forget to add the required mapbox-gl-draw CSS.

like image 90
Andi-lo Avatar answered Oct 25 '22 21:10

Andi-lo


i have install npm install @mapbox/mapbox-gl-draw

added css into angular-cli.json

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

Component

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

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

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

     const draw = new MapboxDraw({
        displayControlsDefault: false,
        controls: {
            polygon: true,
            trash: true
        }
    });
    AppComponent.t.map.addControl(draw);
  }
}
like image 3
Shailesh Ladumor Avatar answered Oct 25 '22 20:10

Shailesh Ladumor