Mapbox Typescript

不想你离开。 提交于 2019-12-03 07:18:33

You can just use the mapbox.js NPM module, and it'll include everything you need.

npm install mapbox.js --save

See this example. We're using Webpack to do the module loading, and with TypeScript you need to explicitly import * for untyped modules.

import * as L from 'mapbox.js';

const map = L.mapbox.map('mapContainer', 'mapbox.streets');

// do stuff.

For anyone like me who just wanted to get a map to show in their project, here's how I got it. Based mostly on Angular2 Mapbox-gl Starter.

Adding Mapbox-gl to Angular 2 - Webpack and Typescript

Install the needed packages...
npm install mapbox-gl --save
npm install @types/mapbox-gl --save
npm install @types/geojson --save

Add stuff to webpack...

module.exports = function(options) {
  return {
    resolve: {
      alias: {
        'mapbox-gl': '../node_modules/mapbox-gl/dist/mapbox-gl.js'
      }
    },
    module: {
      postLoaders: [
        {
          include: /node_modules\/mapbox-gl-shaders/,
          loader: 'transform',
          query: 'brfs'
        }
      ]
    }
  }
}

Add a map.service.ts (For some reason I had to use full relative paths in the imports)...

import { Injectable } from '@angular/core';
import * as mapboxgl from '../../../../node_modules/mapbox-gl/dist/mapbox-gl.js';
import { Map } from '../../../../node_modules/mapbox-gl/dist/mapbox-gl.js';

@Injectable()
export class MapService {
  map: Map<any, any>;

  constructor() {
    (mapboxgl as any).accessToken = 'YOUR_MAPBOX_TOKEN_HERE';
  }
}

Add maps to your component...

import { Component } from '@angular/core';
import { MapService } from '../../api/resources/map.service';
import { Map } from '../../../../node_modules/mapbox-gl/dist/mapbox-gl.js';

@Component({
  selector: 'my-component',
  styles: [ require('./my-component.component.less') ],
  template: require('./my-component.component.html'),
  providers: [ MapService ]
})
export class MyComponentComponent {
  constructor(private mapService: MapService) { }
  ngOnInit() {
    let map = new Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/light-v9',
      zoom: 5,
      center: [-78.880453, 42.897852]
    });

    this.mapService.map = map;
  }
}

Add map div to your html...

// my-component.component.html
<div id="map" class="mapboxgl-map"></div>

For styles, I use LESS, so I imported the mapbox styles there...

// my-component.component.less
@import (less) '../../../../node_modules/mapbox-gl/dist/mapbox-gl.css';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!