Skip to content

Get coordinates of the mouse pointer

Replicates the MapLibre example Get coordinates of the mouse pointer. The map is YAML; the readout is a <pre slot="top-left"> inside <ml-map>. The JavaScript half is the map’s own mousemove event, which carries the pointer’s pixel position (e.point) and its longitude/latitude (e.lngLat).

Move the pointer over the map
get-coordinates-of-the-mouse-pointer.yaml
# yaml-language-server: $schema=https://docs.maplibre-yaml.org/schema/latest/map.schema.json
# Gallery twin of https://maplibre.org/maplibre-gl-js/docs/examples/get-coordinates-of-the-mouse-pointer/
# The YAML half: just the map. Pointer coordinates come from the map's
# mousemove event — see get-coordinates-of-the-mouse-pointer.js; the
# readout rides a corner slot.
type: map
id: get-coordinates-of-the-mouse-pointer
config:
center: [-74.5, 40]
zoom: 3
mapStyle: "https://demotiles.maplibre.org/style.json"

This markup goes inside <ml-map>; children with a slot ride its corner system.

get-coordinates-of-the-mouse-pointer.html
<pre slot="top-left" class="gallery-panel" data-pointer-info>Move the pointer over the map</pre>
get-coordinates-of-the-mouse-pointer.js
// The JavaScript half: the map's own mousemove event. e.point is the pixel
// position relative to the map's top-left corner; e.lngLat is the
// geographic position under the pointer (wrapped into -180..180).
const mapEl = document.querySelector("ml-map");
const info = document.querySelector("[data-pointer-info]");
mapEl.mapReady().then((map) => {
map.on("mousemove", (e) => {
info.textContent = `${JSON.stringify(e.point)}\n${JSON.stringify(e.lngLat.wrap())}`;
});
});
  • e.lngLat.wrap() folds longitudes back into −180…180 when the map shows world copies.
  • For pointer events on a layer’s features, the element’s own ml-map:layer-hover DOM event needs no map API at all — see Get features under the mouse pointer.