简体   繁体   中英

Passing this in click handler on map

I am trying to implement a map in an angular 4 application(using openlayers).I have implemented it this way: Html:

<div id="map" class="map" style="width:80vw;height: 60vh;"></div>

Typescript:
Declaration:

@ViewChild("mapElement") mapElement:ElementRef;
public map:any;

Initialization:

this.map = new ol.Map({
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            })
        ],
        target: 'map',
        view: new ol.View({
            center: [2905830.0672892607,5532192.9828046],
            zoom: 12
        })
    });

In my ts file i also have selectedLat and selectedLon (variables of type any).I want to set those variables based on the coordinates found in the event triggered by the user click on map.To do this i've tried the following:

this.map.on('click',this.some_function);

Some_function:

some_function(evt) {
    this.selectedLon=ol.proj.toLonLat(evt.coordinate)[0];
    this.selectedLat=ol.proj.toLonLat(evt.coordinate)[1];
}

The problem that i encounter is the fact that this(in some_function) is reprezented by the map, not my original component. Is there a way for me to pass the original this element to some_function?

I also tried but failed:

this.map.on('click',{param1:this},this.some_function);

Thank you for your help :)

As Openlayers v4.6.5 documents say, map.on can have three parameters. One is event type, another is listener function, last is optional object that you want to use as this.

So you may need to use this.map.on('click', this.som_function, this)

Bind the data to this.

this.some_function = function(e){
    //this.foo
}
    
var data = { foo: 1 };
this.some_function = this.some_function.bind(data);
this.map.on('click',this.some_function);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM