我调用以下代码来创建map的副本对象,并初始化Leaflet地图。这可以正常工作并加载。但是,onEachFeature和/或clickFeature函数无法正常工作。
var map = {
mapUrl: "",
maxZoom: 18,
minZoom: 2,
map: L.map('worldMap').setView([51.505, -0.09], 2),
create: function(values) {
var instance = Object.create(this);
Object.keys(values).forEach(function(key) {
instance[key] = values[key];
});
return instance;
},
initLeafletMap: function() {
L.tileLayer(this.mapUrl, {
attribution: '',
maxZoom: this.maxZoom,
minZoom: this.minZoom,
id: 'mapbox.streets'
}).addTo(this.map);
//add continents' outlines
$.getJSON("/static/continents.json",
(function(style, onEachFeature, map) {
return function(continents) {
console.log(typeof(continents));
L.geoJson(continents, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
};
}(this.style, this.onEachFeature, this.map))
);
},
style: function() {
return {
weight: 2,
opacity: 1,
color: 'beige',
dashArray: '3',
fillOpacity: 0
};
},
onEachFeature: function(feature, layer) {
layer.on({
click: this.clickFeature
});
},
clickFeature: function(e) {
do something here();
},
因此,当我单击地图时,我知道调用了onEachFeature函数,但没有调用clickFeature。相反,我在控制台中收到此错误:
leaflet.js:5 Uncaught TypeError: Cannot read property 'call' of undefined
at e.fire (leaflet.js:5)
at e._fireDOMEvent (leaflet.js:5)
at e._handleDOMEvent (leaflet.js:5)
at HTMLDivElement.r (leaflet.js:5)
答案 0 :(得分:0)
当您将onEachFeature
方法作为IIFE的参数传递以构建对AJAX调用的回调时,很可能仅需要绑定this.onEachFeature.bind(this)
上下文:
FillData()
顺便说一句,您还可以将click事件侦听器直接附加在Leaflet GeoJSON图层组上,而不是对每个子图层都进行此操作。