Reputation: 25
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.
Upvotes: 1
Views: 406
Reputation: 25
Found the solution by myself: Change this:
this.map.on('click', function (e) {
let x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
this.addMarker(x[0], x[1]);
});
To:
this.map.on('click', (e) => {
let x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
this.addMarker(x[0], x[1]);
});
Upvotes: 0
Reputation: 1115
The problem here is the syntax you are using.
Use this code in the this.map
.
You can do two things.
this.map.on('click', (e) => {
const x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
this.addMarker(x[0], x[1]);
});
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
.
Upvotes: 3
Reputation: 171
You need to store the reference of 'this' to another variable before calling the method.
const self = this;
this.map.on('click', function (e) {
let x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
self.addMarker(x[0], x[1]);
});
In the click event handler, the scope of this changes. Therefore, the addMarker was undefined.
Upvotes: 0