Link

Description

This example demonstrates some of the events that happen when you interact with the viewer (panning/zooming/clicking in the map).

When you click on a building, some information is displayed in a popup, but the full object details are also sent through the event bus.

Demo

Click on a building to see its properties as JSON
Mouse coordinates: ... Map center: ..., zoom: ...

Code

// The code below assumes that an api instance is available from loading and initializing
// the demo-js-api map. This is demonstrated in the "Getting started" example.
// The api instance is made available as window.api for use within your browser's dev console.

// Display mouse coordinates below the map.
api.events.on("map.mouseMove", evt => {
  let formattedCoordinate;
  // Note: evt is null when use moves mouse outside the map viewport.
  if (!evt) {
    formattedCoordinate = "...";
  } else {
    const [x, y] = evt.coordinate;
    formattedCoordinate = `${x.toFixed(2)}, ${y.toFixed(2)}`;
  }
  document.getElementById("mouse-coords").innerText = formattedCoordinate;
});

// Listen for center/zoom changes
api.events.on("map.move", evt => {
  const [centerX, centerY] = evt.center;
  const formattedCenter = `${centerX.toFixed(2)}, ${centerY.toFixed(2)}`;
  document.getElementById("map-center").innerText = formattedCenter;
  document.getElementById("map-zoom").innerText = evt.zoom;
});

// Show raw object data from the first clicked feature as JSON.
api.events.on("featureInfo.received", evt => {
  if (evt.results.length === 0) {
    return;
  }
  const rawData = evt.results[0].properties;
  const rawJson = JSON.stringify(rawData, null, 2);
  document.getElementById("code-block").innerText = rawJson;
});