-1

我正在使用openlayers 5.1.3,我对如何创建单击矢量图层特征的功能感到困惑,得到我点击的那个,然后得到它的属性。我正在关注这个例子,这是我发现的唯一相关的例子。

我有一个空向量源,在搜索后获取 GeoJSON 数据

初始化地图和向量

this.vectorsource = new VectorSource({});

this.vectorlayer = new VectorLayer({
  source: this.vectorsource
});

var selectClick = new Select({
  condition: click
});

this.olmap.addInteraction(selectClick);
selectClick.on('select', function(e) {
  console.log(e.target);
});

搜索后

this.vectorsource.clear();
const fff = (new GeoJSON()).readFeatures(data.data);
this.vectorsource.addFeatures(fff);

selectClickaddInteraction是最接近我想要的东西。我不知道如何继续,我不知道这是否是获取我单击的特定功能的正确方法组合,所以我可以获取它的属性。另外,对我来说奇怪的是,我没有看到getFeature矢量图层的任何(不是普通的)方法或功能。

我该如何进行?

谢谢

4

1 回答 1

4

e.targete选择回调函数的参数在哪里)有一个getFeatures()方法。下面的代码将返回(第一个)选定的功能:

var selectClick = new ol.interaction.Select({
  condition: ol.events.condition.click
});
this.olmap.addInteraction(selectClick);
selectClick.on('select', function(e) {
   var selectedFeatures = e.target.getFeatures().getArray();
   var featuresStr = selectedFeatures[0].get('name');
   console.log(featuresStr);
});

概念证明示例

代码片段:

var raster = new ol.layer.Tile({ // TileLayer({
  source: new ol.source.OSM()
});

var vector = new ol.layer.Vector({ // VectorLayer({
  source: new ol.source.Vector({ // VectorSource({
    url: 'https://cdn.rawgit.com/johan/world.geo.json/master/countries.geo.json',
    format: new ol.format.GeoJSON()
  })
});

var map = new ol.Map({
  layers: [raster, vector],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

var selectClick = new ol.interaction.Select({
  condition: ol.events.condition.click
});

map.addInteraction(selectClick);
selectClick.on('select', function(e) {
  var selectedFeatures = e.target.getFeatures().getArray();
  var featureStr = "none";
  if (!!selectedFeatures && selectedFeatures.length > 0) {
    featureStr = selectedFeatures[0].get('name');
  }
  console.log(featureStr);
  document.getElementById('status').innerHTML = featureStr;
});
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 95%;
  width: 100%;
}
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.1.3/build/ol.js"></script>
<div id="status"></div>
<div id="map" class="map"></div>

于 2018-08-02T01:46:39.753 回答