Files
openlayers/examples/select-hover-features.js
2022-01-07 13:00:35 -07:00

70 lines
1.5 KiB
JavaScript

import Fill from '../src/ol/style/Fill.js';
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import Stroke from '../src/ol/style/Stroke.js';
import Style from '../src/ol/style/Style.js';
import VectorLayer from '../src/ol/layer/Vector.js';
import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
const style = new Style({
fill: new Fill({
color: '#eeeeee',
}),
});
const vector = new VectorLayer({
source: new VectorSource({
url: 'https://openlayers.org/data/vector/ecoregions.json',
format: new GeoJSON(),
}),
background: 'white',
style: function (feature) {
const color = feature.get('COLOR') || '#eeeeee';
style.getFill().setColor(color);
return style;
},
});
const map = new Map({
layers: [vector],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const selectStyle = new Style({
fill: new Fill({
color: '#eeeeee',
}),
stroke: new Stroke({
color: 'rgba(255, 255, 255, 0.7)',
width: 2,
}),
});
const status = document.getElementById('status');
let selected = null;
map.on('pointermove', function (e) {
if (selected !== null) {
selected.setStyle(undefined);
selected = null;
}
map.forEachFeatureAtPixel(e.pixel, function (f) {
selected = f;
selectStyle.getFill().setColor(f.get('COLOR') || '#eeeeee');
f.setStyle(selectStyle);
return true;
});
if (selected) {
status.innerHTML = selected.get('ECO_NAME');
} else {
status.innerHTML = ' ';
}
});