Search code examples
angulartypescriptopenlayers

Unable to call typescript function inside OpenLayers function


I have a problem using OpenLayers with TypeScript in Angular. I have a event listener for my ol map

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

x[0] and x[1] are my lat and lon values. If I call the function addMarker I will receive the error when clicking on the map:

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)

This is my addMarker Method:

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

I don`t know how to fix this problem or if there is a workaround.

I hope you can help me here.


Solution

  • The problem here is the syntax you are using. Use this code in the this.map. You can do two things.

    1. Use arrow function(recommended).
    this.map.on('click', (e) => {
        const x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
        this.addMarker(x[0], x[1]);
    });
    
    1. Store this in variable and then use that variable.
    const _that = this;
    this.map.on('click', function(e) {
        const x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
        _that.addMarker(x[0], x[1]);
    });
    

    The reason being, the scope of this. when you create a function like function(){} this refers to this function, but when you use arrow function the this will refer to class.