Edit

Vector Tile Info

vectortiles5

Getting feature information from vector tiles.

Move your pointer over rendered features to display feature properties.

main.js
import MVT from 'ol/format/MVT.js';
import Map from 'ol/Map.js';
import VectorTileLayer from 'ol/layer/VectorTile.js';
import VectorTileSource from 'ol/source/VectorTile.js';
import View from 'ol/View.js';

const map = new Map({
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
  layers: [
    new VectorTileLayer({
      source: new VectorTileSource({
        format: new MVT(),
        url: 'https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer/tile/{z}/{y}/{x}.pbf',
      }),
    }),
  ],
});

map.on('pointermove', showInfo);

const info = document.getElementById('info');
function showInfo(event) {
  const features = map.getFeaturesAtPixel(event.pixel);
  if (features.length == 0) {
    info.innerText = '';
    info.style.opacity = 0;
    return;
  }
  const properties = features[0].getProperties();
  info.innerText = JSON.stringify(properties, null, 2);
  info.style.opacity = 1;
}
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Vector Tile Info</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
      #map {
        position: relative;
      }

      #info {
        z-index: 1;
        opacity: 0;
        position: absolute;
        bottom: 0;
        left: 0;
        margin: 0;
        background: rgba(0,60,136,0.7);
        color: white;
        border: 0;
        transition: opacity 100ms ease-in;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map">
      <pre id="info"/>
    </div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
{
  "name": "vector-tile-info",
  "dependencies": {
    "ol": "9.1.0"
  },
  "devDependencies": {
    "vite": "^3.2.3"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}