【问题标题】:Openlayers map undefined in a classOpenlayers 在类中映射未定义
【发布时间】:2018-02-18 15:53:02
【问题描述】:

我在 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 类型的对象)

【问题讨论】:

    标签: javascript angular typescript openlayers openlayers-3


    【解决方案1】:

    您的问题是 function () {}() => {} 之间的差异。

    • function () {} 中,“this”的上下文是函数的调用者,所以这里是“OlMap”。
    • () => {} 中,“this”的上下文是您创建它的位置,因此这里是“MapService”。

    this.map 在 OlMap 中不存在。

    要解决您的问题,只需将 function () 替换为 () => 到 this.map.on() 中即可。

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2019-01-25
      • 2023-04-10
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多