[英]Passing this in click handler on map
我正在嘗試在 Angular 4 應用程序中實現地圖(使用 openlayers)。我已經以這種方式實現了它:Html:
<div id="map" class="map" style="width:80vw;height: 60vh;"></div>
打字稿:
宣言:
@ViewChild("mapElement") mapElement:ElementRef;
public map:any;
初始化:
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
})
});
在我的 ts 文件中,我也有 selectedLat 和 selectedLon (任何類型的變量)。我想根據用戶點擊地圖觸發的事件中找到的坐標來設置這些變量。為此,我嘗試了以下方法:
this.map.on('click',this.some_function);
一些功能:
some_function(evt) {
this.selectedLon=ol.proj.toLonLat(evt.coordinate)[0];
this.selectedLat=ol.proj.toLonLat(evt.coordinate)[1];
}
我遇到的問題是 this(in some_function) 由地圖表示,而不是我的原始組件。 有沒有辦法將原始的 this 元素傳遞給 some_function?
我也試過但失敗了:
this.map.on('click',{param1:this},this.some_function);
謝謝您的幫助 :)
正如Openlayers v4.6.5 文檔所說, map.on
可以有三個參數。 一個是事件類型,另一個是偵聽器函數,最后一個是您要用作 this 的可選對象。
所以你可能需要使用this.map.on('click', this.som_function, 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.