OpenLayers图形附加数据与回调
OpenLayers的feature有个feature.values_.data属性,可以为其附加各种自定义数据。
当创建一个feature时:
var myData = {
value0: '文本',
leftClickCallback: function(params) {},
leftClickCallbackParams: {value: 1},
rightClickCallback: function(params) {},
rightClickCallbackParams: {value: 2}
};
var feature = new ol.Feature({
geometry: new ol.geom.Point([0,0]),
data: myData
});
这样就为创建的点feature附加了自定义的数据。
当获取到该点feature时,通过其feature.values_.data属性即可拿到自定义的数据。
若需要点击回调或者执行自定义操作,那么将所要执行的函数和参数从该data中取出,然后将参数传给函数调用即可。
// 左键点击交互
map.on("click", function(event) {
var pixel = map.getEventPixel(event.originalEvent);
map.forEachFeatureAtPixel(pixel, function(feature, layer) {
if(feature) {
var data = feature.values_.data;
if(data && data.leftClickCallback) {
event.clickPoint = self.map.getEventCoordinate(event);
data.leftClickCallback(event, feature, data.leftClickCallbackParams);
}
}
});
});
// 右键点击交互
$(map.getViewport()).on("contextmenu", function(event) {
event.preventDefault(); //屏蔽自带的右键事件
var pixel = [event.offsetX, event.offsetY];
var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
return feature;
});
if(feature) {
var data = feature.values_.data;
if(data && data.rightClickCallback) {
event.clickPoint = map.getEventCoordinate(event);
data.rightClickCallback(event, feature, data.rightClickCallbackParams);
}
}
});
转载自:https://blog.csdn.net/fyyyr/article/details/82959353