Reputation: 55
I have an OpenLayers map
variable like this:
this.map = new Map({
target: 'map',
moveTolerance: 2,
layers: [this.capaFondo, this.capaPropia, this.vector],
view: new View({
projection: proyeccion,
center: fromLonLat([-1.629950, 42.62], proyeccion),
zoom: 9.3
})
});
I'm trying to handle single clicks like this:
this.map.on('singleclick', function(evt) {
const p = new Point(evt.coordinate).transform(this.map.getView().getProjection(), proyeccion);
const properties = ['CP:geometry'];
const featureRequest = new WFS().writeGetFeature({
srsName: 'EPSG:25830',
featurePrefix: 'CP',
featureTypes: ['CadastralParcel'],
outputFormat: 'application/json',
propertyNames: properties,
filter: containsFilter('geometry', p, 'EPSG:25830')
});
}
But inside the function, the map
variable seems to be undefined.
How can I get the map
value inside it? Any help would be great!
Upvotes: 0
Views: 186
Reputation: 488
You have to use arrow function for use global scope of this variable
this.map.on('singleclick', (evt) => {
const p = new Point(evt.coordinate).transform(this.map.getView().getProjection(), proyeccion);
const properties = ['CP:geometry'];
const featureRequest = new WFS().writeGetFeature({
srsName: 'EPSG:25830',
featurePrefix: 'CP',
featureTypes: ['CadastralParcel'],
outputFormat: 'application/json',
propertyNames: properties,
filter: containsFilter('geometry', p, 'EPSG:25830')
});
}
Upvotes: 1
Reputation: 8515
A function
creates a new context. In order to make it work the way you expect you can change function (evt) {}
to arrow function, like this:
this.map.on('singleclick', (evt) => {
const p = new Point(evt.coordinate).transform(this.map.getView().getProjection(), proyeccion);
const properties = ['CP:geometry'];
const featureRequest = new WFS().writeGetFeature({
srsName: 'EPSG:25830',
featurePrefix: 'CP',
featureTypes: ['CadastralParcel'],
outputFormat: 'application/json',
propertyNames: properties,
filter: containsFilter('geometry', p, 'EPSG:25830')
});
}
More on how this
works in JS in this great answer
Upvotes: 1