首页 > 解决方案 > Mapbox GeoJSON line with Angular

问题描述

I am trying to build a simple map using Mapbox, Ionic Framework and Angular and I would like to add a GeoJSON line to the map like this example: https://docs.mapbox.com/mapbox-gl-js/example/geojson-line/

I am new to angular and still learning, so I am sure my TS is messed up. Anyhow, here are my files below:

Packages:

"@angular/common": "~8.2.14", "@angular/core": "~8.2.14", "@angular/fire": "^6.0.0", "@angular/forms": "~8.2.14", "@angular/platform-browser": "~8.2.14", "@angular/platform-browser-dynamic": "~8.2.14", "@angular/router": "~8.2.14", "@capacitor/core": "2.0.2", "@ionic-native/core": "^5.24.0", "@ionic-native/geolocation": "^5.24.0", "@ionic-native/google-maps": "^5.5.0", "@ionic-native/splash-screen": "^5.0.0", "@ionic-native/status-bar": "^5.0.0", "@ionic/angular": "^5.0.0", "cordova-browser": "6.0.0", "cordova-plugin-geolocation": "^4.0.2", "cordova-plugin-googlemaps": "^2.7.1", "core-js": "^2.5.4", "firebase": "^7.14.2", "mapbox-gl": "^1.10.0", "rxjs": "^6.5.5", "save": "^2.4.0", "tslib": "^1.9.0", "zone.js": "~0.9.1"

HTML Page:

<div id="mapbox"></div>

TS Page:

import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import * as Mapboxgl from 'mapbox-gl';

@component({
selector: 'app-map',
templateUrl: './map.page.html',
styleUrls: ['./map.page.scss'],
})
export class MapPage implements OnInit {

map: mapboxgl.Map

ngOnInit() {

(Mapboxgl as any).accessToken = environment.mapboxKey;
this.map = new Mapboxgl.Map({
container: 'mapbox',
style: 'mapbox://styles/mapbox/streets-v11',
center: [35.1715959,31.9305916,],
zoom: 10
});

this.mapmarker();
}

mapmarker(){

this.map.on('load', function() {
this.map.addSource('route', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': [
[35.20620346069335,31.941237613275092],
[35.21341323852539,31.952162238024975],
[35.21392822265624,31.961337918930735],
[35.21100997924805,31.965998231173806],
[35.19899368286133,31.971968910549975],
[35.187835693359375,31.97240577428203],
[35.17822265625,31.967163272276267],
[35.173072814941406,31.958133817062862],
[35.17066955566406,31.950560041013226]
]
}
}
});
this.map.addLayer({
'id': 'route',
'type': 'line',
'source': 'route',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#888',
'line-width': 8
}
});
});

}

}

My Visual Studio Code shows no errors, but when I load the app, I get this error: ERROR TypeError: Cannot read property 'addSource' of undefined

Any help is appreciated.

标签: angularionic-frameworkmapbox-gl

解决方案


我有同样的问题,我也解决了使用和箭头功能

例如:

this.map.on('load', this.loadData);
loadData= () => {
  this.map.addSource('layerName', {
  type: 'geojson',
  data: 'url/json file',
})
.......
}

推荐阅读