Map events and coordinate conversion
Quick answer
This tutorial separates the three coordinate spaces carried by an OpenLayers map event: event.pixel, event.coordinate and event.originalEvent. It uses singleclick with map.forEachFeatureAtPixel, hitTolerance and layerFilter to resolve hits, converts between pixels and coordinates through getCoordinateFromPixel and getPixelFromCoordinate, and throttles pointermove with requestAnimationFrame and hasFeatureAtPixel. Readers can wire clicks, hovers and coordinate readouts that stay accurate at any zoom.
Key points
- Prefer singleclick over click so drags and double clicks do not fire false selections.
- Return a meaningful object from forEachFeatureAtPixel to stop the search early.
- Convert event.coordinate with ol.proj.toLonLat before displaying it to users.
Example
map.on('singleclick', function (event) {
var hit = map.forEachFeatureAtPixel(
event.pixel,
function (feature, layer) {
return { feature: feature, layer: layer };
},
{
hitTolerance: 6,
layerFilter: function (layer) {
return layer.get('queryable') !== false;
}
}
);
if (!hit) {
console.log('空白处', event.coordinate);
return;
}
console.log('命中', hit.feature.get('name'), '图层', hit.layer.get('title'));
});var coord = map.getCoordinateFromPixel([120, 80]);
var pixel = map.getPixelFromCoordinate(coord);
var lngLat = ol.proj.toLonLat(coord);
var viewCoord = ol.proj.fromLonLat([116.397, 39.908]);
console.log(coord, pixel, lngLat, viewCoord);
Notes
- hitTolerance is measured in pixels, so its ground footprint shrinks as you zoom in.
- Reading coordinates during movestart returns the previous frame's view state.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Map events and coordinate conversion. https://www.jingweizhi.com/en/openlayers/tutorials/map-events.html (accessed 2026-11-03).