Friday 12 May 2017

javascript - how can I specify a popup to show only for a specific layer in openLayers 3?


I am using the function to define popup contents in a map, and right now, it createa a popup for every feature I click on the map, no matter what layer it is in. I would like this popup to appear only for features within one layer. I'm sure there is a way I can specify this in the function, but I'm not sure how. I tried using this for line 6 if (feature && layer === layerVector) { but it gave me an error saying that layer is undefined. layerVector is the variable name for the layer I want to use the popup for. Can anyone help? Here is the code:


map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
if (feature) {
popup.setPosition(evt.coordinate);

content.innerHTML = 'Parcel No: '+
feature.get('parcel')+'
'+
'Owner: '+
feature.get('primowner')
}
});

Answer



When doing forEachFeatureAtPixel, you should do any filtrering inside the callback function. You have the feature and it's layer available as arguments.


This would return the first clicked feature:


var feature = map.forEachFeatureAtPixel(pixel,

function(feature, layer) {
return feature;
}
);

This would return the first clicked feature in targetLayer:


var feature = map.forEachFeatureAtPixel(pixel,
function(feature, layer) {
if (layer == targetLayer) {
return feature;

}
}
);

But when you know that you are only interested in a set of specific layers, a simple optimization is to use the fourth argument: the layer filter function.


The layer filter function is called once for each vector layer, and determines if the layer should be used when looking for features at the given pixel. The code above would trigger an unnecessary spatial lookup in all vector layers, while the code below will only look for matching features in targetLayer:


var feature = map.forEachFeatureAtPixel(pixel,
function (feature, layer) {
return feature;
},

this, // third argument, determines 'this' for the callback
function (layer) {
return layer == targetLayer;
}
);

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...