Update box selection example

This commit is contained in:
Tim Schaub
2022-01-01 09:37:40 -07:00
parent 539eae1398
commit faddbf098b
4 changed files with 39 additions and 19 deletions

View File

@@ -1,4 +1,3 @@
.ol-dragbox {
background-color: rgba(255,255,255,0.4);
border-color: rgba(100,150,0,1);
#map {
background: #1a2b39;
}

View File

@@ -9,4 +9,4 @@ docs: >
tags: "DragBox, feature, selection, box"
---
<div id="map" class="map"></div>
<div id="info">No countries selected</div>
<div>Selected regions: <span id="info">None</span></div>

View File

@@ -1,23 +1,32 @@
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import VectorLayer from '../src/ol/layer/Vector.js';
import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import {DragBox, Select} from '../src/ol/interaction.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {Fill, Stroke, Style} from '../src/ol/style.js';
import {platformModifierKeyOnly} from '../src/ol/events/condition.js';
const vectorSource = new VectorSource({
url: 'data/geojson/countries.geojson',
url: 'https://openlayers.org/data/vector/ecoregions.json',
format: new GeoJSON(),
});
const style = new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.6)',
}),
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
new VectorLayer({
source: vectorSource,
style: function (feature) {
const color = feature.get('COLOR_BIO') || '#eeeeee';
style.getFill().setColor(color);
return style;
},
}),
],
target: 'map',
@@ -28,8 +37,24 @@ const map = new Map({
}),
});
const selectedStyle = new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.6)',
}),
stroke: new Stroke({
color: 'rgba(255, 255, 255, 0.7)',
width: 2,
}),
});
// a normal select interaction to handle click
const select = new Select();
const select = new Select({
style: function (feature) {
const color = feature.get('COLOR_BIO') || '#eeeeee';
selectedStyle.getFill().setColor(color);
return selectedStyle;
},
});
map.addInteraction(select);
const selectedFeatures = select.getFeatures();
@@ -85,11 +110,11 @@ const infoBox = document.getElementById('info');
selectedFeatures.on(['add', 'remove'], function () {
const names = selectedFeatures.getArray().map(function (feature) {
return feature.get('name');
return feature.get('ECO_NAME');
});
if (names.length > 0) {
infoBox.innerHTML = names.join(', ');
} else {
infoBox.innerHTML = 'No countries selected';
infoBox.innerHTML = 'None';
}
});

View File

@@ -17,12 +17,8 @@ const vectorLayer = new VectorLayer({
format: new GeoJSON(),
}),
style: function (feature) {
const color = feature.get('COLOR');
if (color) {
const color = feature.get('COLOR') || '#eeeeee';
style.getFill().setColor(color);
} else {
style.getFill().setColor('#eeeeee');
}
return style;
},
});