如何获取具有文本样式的点几何图形的特征?

问题描述 投票:0回答:1

在代码片段中,我添加了一个带有文本样式的单点功能(

brokenStyle
)。

我想知道我的光标何时移到此功能上,但

getFeatures
总是返回一个空列表。

如果我使用

workingStyle
(使用 Circle 样式),我将看到
Hit Feature
出现在控制台中。

为什么文本样式在这种情况下不起作用?如果我想使用文本样式,我是否还需要使用透明的圆形或正方形,以便

getFeatures
可以工作?这种情况下的常见做法是什么?

ol.proj.get("EPSG:4326").setExtent([-180, -85, 180, 85]);

const osm = new ol.source.OSM();
osm.setTileGridForProjection(
  "EPSG:4326",
  ol.tilegrid.createXYZ({ extent: [-180, -90, 180, 90] })
);

const feature = new ol.Feature({
  geometry: new ol.geom.Point([0, 45])
});

const source = new ol.source.Vector();
source.addFeatures([feature]);

const brokenStyle = new ol.style.Style({
  text: new ol.style.Text({
    text: "X",
    scale: 1.0,
    textBaseline: "bottom",
    fill: new ol.style.Fill({ color: "#000000" }),
    stroke: new ol.style.Stroke({ color: "black", width: 1 })
  })
});

const workingStyle = new ol.style.Style({
  image: new ol.style.Circle({
    radius: 5,
    stroke: new ol.style.Stroke({
      color: "black",
      width: 2
    }),
    fill: new ol.style.Fill({
      color: "black"
    })
  })
});

const vectorLayer = new ol.layer.Vector({
  source,
  style: (feature) => {
    return brokenStyle;
  }
});

const map = new ol.Map({
  target: "map",
  layers: [
    new ol.layer.Tile({
      source: osm
    }),
    vectorLayer
  ],
  view: new ol.View({
    projection: "EPSG:4326",
    center: [0, 0],
    zoom: 0
  })
});

map.on("pointermove", (e) => {
  const pixel = e.pixel;

  vectorLayer.getFeatures(e.pixel).then((hitFeatures) => {
    if (hitFeatures.length > 0) {
      console.log("Hit Feature");
    }
  });
});
#map {
  aspect-ratio: 360/170;
  background-color: blue;
  margin: 32px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/7.3.0/ol.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/7.3.0/dist/ol.min.js"></script>
<div id="map"></div>

openlayers
1个回答
0
投票

“不考虑文本”https://openlayers.org/en/latest/apidoc/module-ol_layer_Vector-VectorLayer.html#getFeatures因此您需要使用

map.getFeaturesAtPixel()
代替:

map.on("pointermove", (e) => {
  const pixel = e.pixel;

  const hitFeatures = map.getFeaturesAtPixel(e.pixel, {
   layerFilter: (l) => l === vectorLayer
  )
  if (hitFeatures.length > 0) {
    console.log("Hit Feature");
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.