简体   繁体   English

在地图上的点击处理程序中传递它

[英]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:我正在尝试在 Angular 4 应用程序中实现地图(使用 openlayers)。我已经以这种方式实现了它: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:在我的 ts 文件中,我也有 selectedLat 和 selectedLon (任何类型的变量)。我想根据用户点击地图触发的事件中找到的坐标来设置这些变量。为此,我尝试了以下方法:

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.我遇到的问题是 this(in some_function) 由地图表示,而不是我的原始组件。 Is there a way for me to pass the original this element to some_function?有没有办法将原始的 this 元素传递给 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.正如Openlayers v4.6.5 文档所说, map.on可以有三个参数。 One is event type, another is listener function, last is optional object that you want to use as this.一个是事件类型,另一个是侦听器函数,最后一个是您要用作 this 的可选对象。

So you may need to use this.map.on('click', this.som_function, this)所以你可能需要使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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