Skip to content

Icon Sprites 与 WebGL ​

Icon Sprites 与 WebGL示例。 WebGL 图标 精灵 point ufo

本示例展示如何使用 ol/layer/WebGLVector 渲染 数量非常庞大的精灵(sprite)。上面的地图基于来自美国国家 UFO 报告中心(National UFO Reporting Center)的数据集:每个 图标根据其报告的形状(圆盘、光点、火球等)标记一次 UFO 目击事件。目击事件越久远,图标颜色越偏红。

示例使用了一个非常简单的精灵图集,即一个 PNG 文件,其中所有图标按网格排列。然后,通过传给 ol/layer/WebGLVector 构造函数的 style 对象 根据目击事件的形状指定使用哪个精灵。

该数据集包含大约 8 万个点,可在此处找到:https://www.kaggle.com/NUFORC/ufo-sightings

main.js
js
import Feature from 'ol/Feature.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Point from 'ol/geom/Point.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import WebGLVectorLayer from 'ol/layer/WebGLVector.js';
import {fromLonLat} from 'ol/proj.js';
import ImageTile from 'ol/source/ImageTile.js';
import VectorSource from 'ol/source/Vector.js';

const key = 'Get your own API key at https://www.maptiler.com/cloud/';
const attributions =
  '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
  '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';

const map = new Map({
  layers: [
    new TileLayer({
      source: new ImageTile({
        attributions: attributions,
        url:
          'https://api.maptiler.com/maps/satellite/{z}/{x}/{y}.jpg?key=' + key,
      }),
    }),
  ],
  target: document.getElementById('map'),
  view: new View({
    center: [0, 4000000],
    zoom: 2,
  }),
});

const oldColor = [255, 160, 110];
const newColor = [180, 255, 200];

const style = {
  'icon-src': 'data/ufo_shapes.png',
  'icon-width': 128,
  'icon-height': 64,
  'icon-color': [
    'interpolate',
    ['linear'],
    ['get', 'year'],
    1950,
    oldColor,
    2013,
    newColor,
  ],
  'icon-offset': [
    'match',
    ['get', 'shape'],
    'light',
    [0, 0],
    'sphere',
    [32, 0],
    'circle',
    [32, 0],
    'disc',
    [64, 0],
    'oval',
    [64, 0],
    'triangle',
    [96, 0],
    'fireball',
    [0, 32],
    [96, 32],
  ],
  'icon-size': [32, 32],
  'icon-scale': 0.5,
};

const pointsLayer = new WebGLVectorLayer({
  variables: {
    filterShape: 'all',
  },
  source: new VectorSource({
    features: [],
    attributions: 'National UFO Reporting Center',
  }),
  style: [
    {
      style,
      filter: [
        'any',
        ['==', ['var', 'filterShape'], 'all'],
        ['==', ['var', 'filterShape'], ['get', 'shape']],
      ],
    },
  ],
});

const shapeSelect = document.getElementById('shape-filter');
shapeSelect.addEventListener('input', function () {
  pointsLayer.updateStyleVariables({filterShape: shapeSelect.value});
  map.render();
});
function fillShapeSelect(shapeTypes) {
  Object.keys(shapeTypes)
    .sort(function (a, b) {
      return shapeTypes[b] - shapeTypes[a];
    })
    .forEach(function (shape) {
      const option = document.createElement('option');
      const sightings = shapeTypes[shape];
      option.text = `${shape} (${sightings} sighting${
        sightings === 1 ? '' : 's'
      })`;
      option.value = shape;
      shapeSelect.appendChild(option);
    });
}

const client = new XMLHttpRequest();
client.open('GET', 'data/csv/ufo_sighting_data.csv');
client.addEventListener('load', function () {
  const csv = client.responseText;
  // 键为形状名称,值为目击次数
  const shapeTypes = {};
  const features = [];

  let prevIndex = csv.indexOf('\n') + 1; // 跳过表头行
  let curIndex;
  while ((curIndex = csv.indexOf('\n', prevIndex)) !== -1) {
    const line = csv.substring(prevIndex, curIndex).split(',');
    prevIndex = curIndex + 1;

    const coords = [parseFloat(line[5]), parseFloat(line[4])];
    const shape = line[2];
    shapeTypes[shape] = (shapeTypes[shape] || 0) + 1;

    features.push(
      new Feature({
        datetime: line[0],
        year: parseInt(/[0-9]{4}/.exec(line[0])[0], 10), // 将年份提取为整数
        shape: shape,
        duration: line[3],
        geometry: new Point(fromLonLat(coords)),
      }),
    );
  }
  shapeTypes['all'] = features.length;
  pointsLayer.getSource().addFeatures(features);
  map.addLayer(pointsLayer);
  fillShapeSelect(shapeTypes);
});
client.send();

const info = document.getElementById('info');
map.on('pointermove', function (evt) {
  if (map.getView().getInteracting() || map.getView().getAnimating()) {
    return;
  }
  const text = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
    const datetime = feature.get('datetime');
    const duration = feature.get('duration');
    const shape = feature.get('shape');
    return `On ${datetime}, lasted ${duration} seconds and had a "${shape}" shape.`;
  });
  info.innerText = text || '';
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>图标精灵与 WebGL</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <div>当前目击事件: <span id="info"></span></div>
    <div>
      <label for="shape-filter">按 UFO 形状筛选:</label>
      <select id="shape-filter"></select>
    </div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "icon-sprite-webgl",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}