Shows bad behavior of hit detection with hit tolerance.
Hover over the map and observe how the small circles get a black outline as you hover over them. Is the expected feature getting highlighted?
import 'ol/ol.css';
import CircleStyle from 'ol/style/Circle';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import {Fill, Stroke, Style} from 'ol/style';
import {Point} from 'ol/geom';
const map = new Map({
target: 'map',
view: new View({
center: [0, 0],
resolution: 1,
resolutions: [1],
}),
});
const vectorLayer = new VectorLayer({
source: new VectorSource({
features: [
new Feature({
geometry: new Point([0, 0]),
color: 'white',
}),
new Feature({
geometry: new Point([-10, 0]),
color: 'fuchsia',
}),
new Feature({
geometry: new Point([-10, -10]),
color: 'orange',
}),
new Feature({
geometry: new Point([-10, 10]),
color: 'cyan',
}),
],
}),
style: (feature) => {
return new Style({
image: new CircleStyle({
radius: 5,
fill: new Fill({
color: feature.get('color'),
}),
stroke: new Stroke({
color: 'gray',
width: 1,
}),
}),
});
},
});
map.addLayer(vectorLayer);
const highlightFeature = new Feature(new Point([NaN, NaN]));
highlightFeature.setStyle(
new Style({
image: new CircleStyle({
radius: 5,
stroke: new Stroke({
color: 'black',
width: 2,
}),
}),
})
);
vectorLayer.getSource().addFeature(highlightFeature);
map.on('pointermove', (e) => {
const hit = map.forEachFeatureAtPixel(
e.pixel,
(feature) => {
highlightFeature.setGeometry(feature.getGeometry().clone());
return true;
},
{
hitTolerance: 10,
}
);
if (!hit) {
highlightFeature.setGeometry(new Point([NaN, NaN]));
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hit tolerance priority</title>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep"></script>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL,TextDecoder,Number.isInteger"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="main.js"></script>
</body>
</html>
{
"name": "hit-tolerance-priority",
"dependencies": {
"ol": "6.6.1"
},
"devDependencies": {
"parcel": "^2.0.0-beta.1"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --public-url . index.html"
}
}