Atlaslog
Atlaslog / OpenLayers / Tutorial / Map events and coordinate conversion
OpenLayers · Tutorial

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.

Last verified 2026-11-03 · OpenLayers 10.3.1 · Cite this page
Key points
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
Runnable examplesChinese originalAll Tutorials
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Cite this page

Atlaslog (2026). Map events and coordinate conversion. https://www.jingweizhi.com/en/openlayers/tutorials/map-events.html (accessed 2026-11-03).