【问题标题】:【openlayer】add a feature to layer,but can not get the feature by click event,how to resolve the problem【openlayer】添加一个特征到图层,但是点击事件无法获取该特征,如何解决
【发布时间】:2021-09-16 17:01:27
【问题描述】:

问题

开放层 版本:6.4.3

添加一个由SVG字符串创建的特征到地图,然后点击地图上的特征,但无法从回调函数中获取该特征。但是,我使用 nomarl 图像 url 制作了一个特征,我可以通过点击地图上的特征来获得特征。

我该如何解决这个问题

代码

import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import Point from 'ol/geom/Point';
import TileJSON from 'ol/source/TileJSON';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import {Icon, Style} from 'ol/style';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';

const iconFeature = new Feature({
  geometry: new Point([0, 0]),
  name: 'Null Island',
  population: 4000,
  rainfall: 500,
});
const src =
  `data:image/svg+xml;utf8,` +
  `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" >` +
  `<path d='M0,0 L0,60 L90,30 z'/>` +
  "</svg>";

const iconStyle = new Style({
  image: new Icon({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    src,
  }),
});

iconFeature.setStyle(iconStyle);

const vectorSource = new VectorSource({
  features: [iconFeature],
});

const vectorLayer = new VectorLayer({
  source: vectorSource,
});

const rasterLayer = new TileLayer({
  source: new TileJSON({
    url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json?secure=1',
    crossOrigin: '',
  }),
});

const target = document.getElementById('map');
const map = new Map({
  layers: [rasterLayer, vectorLayer],
  target: target,
  view: new View({
    center: [0, 0],
    zoom: 3,
  }),
});
map.on("click", function (evt) {
  const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
    return feature;
  });
  // when i click the feature area,i can't get the feature
  console.log(feature) //undefined
});

result

【问题讨论】:

    标签: javascript openlayers openlayers-3 openlayers-6 openlayers-5


    【解决方案1】:

    SVG 需要宽度和高度才能与 OpenLayers 命中检测配合使用

    const src =
      `data:image/svg+xml;utf8,` +
      `<svg width="90" height="60" version="1.1" xmlns="http://www.w3.org/2000/svg" >` +
      `<path d='M0,0 L0,60 L90,30 z'/>` +
      "</svg>";
    

    【讨论】:

    • SVG 图标也可以在地图上显示,没有高度和宽度。是openlayers的bug吗?
    • 在不知道正确大小的情况下,很难分析像素以找到应该进行命中检测的非透明区域。
    • 好的,非常感谢
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2015-05-29
    • 2013-12-21
    • 2018-03-28
    • 2020-06-03
    • 2014-10-10
    相关资源
    最近更新 更多