Example of a vector layer rendered using WebGL
The ecoregions are loaded from a GeoJSON file.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import WebGLVectorLayer from 'ol/layer/WebGLVector.js';
import OSM from 'ol/source/OSM.js';
import VectorSource from 'ol/source/Vector.js';
const style = [
{
filter: ['==', ['var', 'highlightedId'], ['id']],
style: {
'stroke-color': 'white',
'stroke-width': 3,
'stroke-offset': -1,
'fill-color': [255, 255, 255, 0.4],
},
},
{
else: true,
style: {
'stroke-color': ['*', ['get', 'COLOR'], [220, 220, 220]],
'stroke-width': 2,
'stroke-offset': -1,
'fill-color': ['*', ['get', 'COLOR'], [255, 255, 255, 0.6]],
},
},
];
const osm = new TileLayer({
source: new OSM(),
});
const vectorLayer = new WebGLVectorLayer({
source: new VectorSource({
url: 'https://openlayers.org/data/vector/ecoregions.json',
format: new GeoJSON(),
}),
style,
variables: {
highlightedId: -1,
},
});
const map = new Map({
layers: [osm, vectorLayer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 1,
}),
});
let highlightedId = -1;
const displayFeatureInfo = function (pixel) {
const feature = map.forEachFeatureAtPixel(pixel, function (feature) {
return feature;
});
const info = document.getElementById('info');
if (feature) {
info.innerHTML = feature.get('ECO_NAME') || ' ';
} else {
info.innerHTML = ' ';
}
const id = feature ? feature.getId() : -1;
if (id !== highlightedId) {
highlightedId = id;
vectorLayer.updateStyleVariables({highlightedId});
}
};
map.on('pointermove', function (evt) {
if (evt.dragging) {
return;
}
displayFeatureInfo(evt.pixel);
});
map.on('click', function (evt) {
displayFeatureInfo(evt.pixel);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGL Vector Layer</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<div id="info"> </div>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "webgl-vector-layer",
"dependencies": {
"ol": "10.5.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}