无法在OpenLayers函数内部调用Typescript函数

我在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);
}

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

希望您能在这里为我提供帮助。

brqtmars 回答:无法在OpenLayers函数内部调用Typescript函数

这里的问题是您使用的语法。 在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:4326')
    _that.addMarker(x[0],x[1]);
});

原因是this的范围。当您创建类似function(){}的函数时,它是指此函数,但是当您使用arrow函数时,this将指class

,

在调用该方法之前,您需要将“ this”的引用存储到另一个变量中。

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

在click事件处理程序中,此操作的范围发生了变化。因此,addMarker未定义。

,

我自己找到了解决方案: 更改此:

 this.map.on('click','EPSG:4326')
      this.addMarker(x[0],x[1]);
    });

收件人:

this.map.on('click',(e) => {
      let x = transform(e.coordinate,x[1]);
    });
本文链接:https://www.f2er.com/3132865.html

大家都在问