首页 > 解决方案 > 无法在 OpenLayers 函数中调用打字稿函数

问题描述

我在 Angular 中使用 OpenLayers 和 TypeScript 时遇到问题。我的 ol 地图有一个事件监听器

  this.map.on('click', function (e) {
      let x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
      this.addMarker(x[0], x[1]);
    });

x[0] 和 x[1] 是我的纬度和经度值。如果我调用函数 addMarker 我会在点击地图时收到错误消息:

ERROR TypeError: this.addMarker is not a function
at Map.<anonymous> (map.component.ts:90)
at Map.push.../node_modules/ol/events/Target.js.Target.dispatchEvent (Target.js:113)
at Map.push.../node_modules/ol/PluggableMap.js.PluggableMap.handleMapBrowserEvent (PluggableMap.js:871)
at MapBrowserEventHandler.push.../node_modules/ol/events/Target.js.Target.dispatchEvent (Target.js:113)
at MapBrowserEventHandler.push.../node_modules/ol/MapBrowserEventHandler.js.MapBrowserEventHandler.emulateClick_ (MapBrowserEventHandler.js:97)
at MapBrowserEventHandler.push.../node_modules/ol/MapBrowserEventHandler.js.MapBrowserEventHandler.handlePointerUp_ (MapBrowserEventHandler.js:148)
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:39680)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)

这是我的 addMarker 方法:

addMarker(lon, lat) {
  let marker = new Feature({
    geometry: new Point(transform([lon + 0.01, lat], 'EPSG:4326', 'EPSG:3857'))
  });
  this.source.addFeature(marker);
}

我不知道如何解决此问题或是否有解决方法。

我希望你能在这里帮助我。

标签: angulartypescriptopenlayers

解决方案


这里的问题是您使用的语法。在this.map. 你可以做两件事。

  1. 使用箭头功能(推荐)。
this.map.on('click', (e) => {
    const x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
    this.addMarker(x[0], x[1]);
});
  1. 存储this在变量中,然后使用该变量。
const _that = this;
this.map.on('click', function(e) {
    const x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
    _that.addMarker(x[0], x[1]);
});

原因是,范围this。当你创建这样的function(){}函数时,指的是这个函数,但是当你使用arrow函数时,this将引用class.


推荐阅读