我有一个开放街道地图和一些出现在道路上的向量(线)。当我点击向量时,我能够获得该向量的特征,但是我只能通过精确点击向量的像素来实现。有没有办法点击“附近”。矢量(可能偏离几个像素)来获取信息所以我不必那么精确?
当我点击向量时,这是我目前用来获取功能的内容:
var displayFeatureInfo = function (pixel, coordinate) {
var features = [];
map.forEachFeatureAtPixel(pixel, function (feature, layer) {
features.push(feature); // Pushes each feature found into the array
});
if (features.length > 0) { // If there are one or more features
$("#popup").html('<object data=' + "http://URLToLoadDataFrom '/>'); // Load the data using jQuery
popup.setPositioning('top-left');
popup.setPosition(coordinate);
container.style.display = 'block';
} else {
container.style.display = 'none';
}
};
map.on('click', function (evt) {
var coordinate = evt.coordinate;
displayFeatureInfo(evt.pixel, coordinate);
});
提前致谢。
答案 0 :(得分:2)
您可以使用范围而不是单个点来构建提供的像素范围内的范围,并使您的要素选择基础。思想,这意味着您必须使用vector.getSource().forEachFeatureIntersectingExtent
方法而不是map.forEachFeatureAtPixel
。
选中此项(fiddle here):
var displayFeatureInfo = function (pixel, coordinate) {
var features = [];
//this is the offset in pixels. Adjust it to fit your needs
var pixelOffSet = 5;
var pixelWithOffsetMin = [pixel[0]-pixelOffSet,pixel[1]+pixelOffSet];
var pixelWithOffsetMax = [pixel[0]+pixelOffSet,pixel[1]-pixelOffSet];
var XYMin =map.getCoordinateFromPixel(pixelWithOffsetMin)
var XYMax =map.getCoordinateFromPixel(pixelWithOffsetMax)
var extent = XYMax.concat(XYMin);
var extentFeat= new ol.Feature(new ol.geom.Polygon([[
[extent[0],extent[1]],
[extent[0],extent[3]],
[extent[2],extent[3]],
[extent[2],extent[1]],
[extent[0],extent[1]]
]]));
vector.getSource().forEachFeatureIntersectingExtent(extentFeat.getGeometry().getExtent(),
function (feature) {
features.push(feature); // Pushes each feature found into the array
});
if (features.length > 0) { // If there are one or more features
console.log("features found on offset clicked",features)
// container.style.display = 'block';
} else {
console.log("no features on offset click")
}
};
map.on('click', function (evt) {
var coordinate = evt.coordinate;
displayFeatureInfo(evt.pixel, coordinate);
});