class 中未定义的 Openlayers 地图
Openlayers map undefined in a class
我是 angular 的新人(通常 javascript)。我有这个代码
import {Injectable, OnInit} from '@angular/core';
import OlMap from 'ol/map';
import OSM from 'ol/source/osm'
import OlXYZ from 'ol/source/xyz';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/view';
import OlProj from 'ol/proj';
@Injectable()
export class MapService {
public map: OlMap;
private _source: OlXYZ;
private _layer: OlTileLayer;
private _view: OlView;
constructor() { }
/**
* Function initializes the map
* @returns {} Object of map
*/
initMap() {
this._source = new OSM({
});
this._layer = new OlTileLayer({
source: this._source
});
this._view = new OlView({
center: OlProj.fromLonLat([6.661594, 50.433237]),
zoom: 10,
});
this.map = new OlMap({
target: 'map',
layers: [this._layer],
view: this._view
});
this.map.on("moveend", function () {
console.log(this.map);
})
}
}
问题出在最后一行。我正在尝试在 moveend 上控制台记录地图对象(因此当用户拖动地图并释放按钮时 - 我想加载一些数据取决于地图的中心)。 但控制台显示对象 this.map 未定义(即使我在该对象上调用方法并且它工作正常 - 它在鼠标按钮释放时调用。
我想这会是一些 javascript 特殊的东西,一些本地或全局对象引用等
有人能帮帮我吗?
注意:在地图组件中调用 initMap() 方法是这样的
ngOnInit() {
this.map = this.mapService.initMap();
console.log(this.mapService.map);
}
(在这种 console.log 情况下它工作正常,存在 _ol_map 类型的对象)
您的问题是 function () {}
和 () => {}
之间的差异。
- 在
function () {}
中,"this"的上下文是函数的调用者所以这里是"OlMap"。
- 在
() => {}
中,"this" 的上下文是您创建它的地方,所以这里是 "MapService"。
this.map在OlMap中不存在。
要解决您的问题,只需将 function ()
替换为 () =>
为 this.map.on().
我是 angular 的新人(通常 javascript)。我有这个代码
import {Injectable, OnInit} from '@angular/core';
import OlMap from 'ol/map';
import OSM from 'ol/source/osm'
import OlXYZ from 'ol/source/xyz';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/view';
import OlProj from 'ol/proj';
@Injectable()
export class MapService {
public map: OlMap;
private _source: OlXYZ;
private _layer: OlTileLayer;
private _view: OlView;
constructor() { }
/**
* Function initializes the map
* @returns {} Object of map
*/
initMap() {
this._source = new OSM({
});
this._layer = new OlTileLayer({
source: this._source
});
this._view = new OlView({
center: OlProj.fromLonLat([6.661594, 50.433237]),
zoom: 10,
});
this.map = new OlMap({
target: 'map',
layers: [this._layer],
view: this._view
});
this.map.on("moveend", function () {
console.log(this.map);
})
}
}
问题出在最后一行。我正在尝试在 moveend 上控制台记录地图对象(因此当用户拖动地图并释放按钮时 - 我想加载一些数据取决于地图的中心)。 但控制台显示对象 this.map 未定义(即使我在该对象上调用方法并且它工作正常 - 它在鼠标按钮释放时调用。
我想这会是一些 javascript 特殊的东西,一些本地或全局对象引用等
有人能帮帮我吗?
注意:在地图组件中调用 initMap() 方法是这样的
ngOnInit() {
this.map = this.mapService.initMap();
console.log(this.mapService.map);
}
(在这种 console.log 情况下它工作正常,存在 _ol_map 类型的对象)
您的问题是 function () {}
和 () => {}
之间的差异。
- 在
function () {}
中,"this"的上下文是函数的调用者所以这里是"OlMap"。 - 在
() => {}
中,"this" 的上下文是您创建它的地方,所以这里是 "MapService"。
this.map在OlMap中不存在。
要解决您的问题,只需将 function ()
替换为 () =>
为 this.map.on().