我使用的是openlayers 5.1.3,我对如何创建单击矢量层要素的功能,完全获得单击的要素并获得其属性的功能感到困惑。我正在遵循this的示例,这是我发现的唯一相关示例。
我有一个空的向量源,可以在搜索后获取GeoJSON数据
初始化地图和矢量
Map(PointerArgType dataPtr, Index size, const StrideType & stride = StrideType() )
搜索后
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);
和selectClick
最接近我想要的东西。我不知道如何进行,而且我不知道这是否是获得我单击的特定功能的方法的正确组合,因此我可以获取其属性。另外,令我感到奇怪的是,我看不到矢量层的任何addInteraction
(不是复数)方法或功能。
我该如何进行?
谢谢
答案 0 :(得分:3)
e.target
(其中e
是select回调函数的参数)具有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>