[英]Ionic2 Leaflet marker onClick event with geoJson
I am getting an error when adding onClick event to a marker, generated by GeoJSON.将 onClick 事件添加到由 GeoJSON 生成的标记时,出现错误。 I have tried using the following:
我尝试使用以下方法:
layer.on(‘click’, (e)=> {this.onMapClick(e)});
The error I receive when clicked is单击时我收到的错误是
ERROR TypeError: _this.onMapClick is not a function
错误类型错误:_this.onMapClick 不是函数
onMapClick(e) {
console.log(e.latlng.lng, e.latlng.lat)
}
initMap() {
this.MapData.getPoints().subscribe((res) => {
this.markers = res;
function oneachFeature(feature, layer) {
layer.bindPopup(feature.properties.description);
layer.on('click', (e) => {
this.onMapClick(e)
});
}
var myLayer = L.geoJSON(this.markers, {
pointToLayer: function(feature, latlng) {
if (feature.properties.route === "red") {
var smallIcon = new L.Icon({
iconSize: [27, 27],
iconAnchor: [13, 27],
popupAnchor: [1, -24],
iconUrl: 'assets/images/redx2.png'
});
return L.marker(latlng, {
icon: smallIcon
});
} else if (feature.properties.route === "blue") {
var smallIcon = new L.Icon({
iconSize: [27, 27],
iconAnchor: [13, 27],
popupAnchor: [1, -24],
iconUrl: 'assets/images/bluex2.png'
});
return L.marker(latlng, {
icon: smallIcon
});
}
},
onEachFeature: oneachFeature
})
myLayer.addTo(this.map);
});
}
Issue : You are losing the scope( this
) via onEachFeature: oneachFeature
, You can maintain the scope via one of the below methods.问题:您正在通过
onEachFeature: oneachFeature
失去范围( this
),您可以通过以下方法之一维护范围。
All you need is to bind(this)
:您只需要
bind(this)
:
onEachFeature: oneachFeature.bind(this)
OR Use ES6 (Fat Arrow Operator)或使用 ES6(粗箭头运算符)
onEachFeature: (feature, layer) => oneachFeature(feature, layer)
OR或者
onEachFeature : (feature, layer) => {
layer.bindPopup(feature.properties.description);
layer.on('click', (e) => {
this.onMapClick(e)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.