五章-56-划框多选要素
2020-03-27 本文已影响0人
彩云飘过
本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。
源码 见 1056.html ,对应的 官网示例
https://openlayers.org/en/latest/examples/box-selection.html?q=drag
ol.source.forEachFeatureIntersectingExtent
遍历所有在划定的extent内的要素

ctrl +drag

<!DOCTYPE html>
<html>
<head>
<title>划框多选要素</title>
<link rel="stylesheet" href="../include/ol.css" type="text/css" />
<script src="../include/ol.js"></script>
</head>
<style></style>
<body>
<div id="info">没有对象被选择</div>
<div id="map" class="map"></div>
<script>
var vectorSource = new ol.source.Vector({
url: '../data/lands.geojson',
format: new ol.format.GeoJSON()
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: vectorSource
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
//实现对要素的选择
var select = new ol.interaction.Select();
map.addInteraction(select);
var selectedFeatures = select.getFeatures();//保存所有选择到的要素集合
//DragBox interaction对象,用来实现画框选择
var dragBox = new ol.interaction.DragBox({
//检测ctrl键是否被按下
condition: ol.events.condition.platformModifierKeyOnly
});
map.addInteraction(dragBox);
dragBox.on('boxend', function() {
var extent = dragBox.getGeometry().getExtent();//获取划框的四至
vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {//在划框的四至中对所有要素进行遍历,把四至中所有要素放到已选择要素的集合中
selectedFeatures.push(feature);
});
});
dragBox.on('boxstart', function() {
selectedFeatures.clear();
});
var infoBox = document.getElementById('info');
//选中或者移出选择要素时,更新文本展示
selectedFeatures.on(['add', 'remove'], function() {
var names = selectedFeatures.getArray().map(function(feature) {
return feature.get('name');
});
if (names.length > 0) {
infoBox.innerHTML = names.join(', ');
} else {
infoBox.innerHTML = 'No countries selected';
}
});
</script>
</body>
</html>