Skip to content

Earthquakes 与 custom symbols ​

Earthquakes 与 custom symbols示例。 KML 矢量 样式 canvas symbol

本示例解析一个 KML 文件,并将要素渲染为矢量图层。该图层被赋予了一个 style,使用自定义的闪电符号、以与震级相关的大小来渲染地震位置。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {getBottomLeft, getTopRight} from 'ol/extent.js';
import KML from 'ol/format/KML.js';
import Polygon from 'ol/geom/Polygon.js';
import {DEVICE_PIXEL_RATIO} from 'ol/has.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import {toContext} from 'ol/render.js';
import StadiaMaps from 'ol/source/StadiaMaps.js';
import VectorSource from 'ol/source/Vector.js';
import Fill from 'ol/style/Fill.js';
import Icon from 'ol/style/Icon.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';

const getSymbolOutline = (function () {
  const path = [
    [0, 0],
    [4, 2],
    [6, 0],
    [10, 5],
    [6, 3],
    [4, 5],
    [0, 0],
  ];
  const symbolOutline = new Polygon([path]);
  symbolOutline.rotate(1.2, path[0]);
  return function (scale, offset) {
    const outline = symbolOutline.clone();
    outline.scale(scale, scale, path[0]);
    const origin = getBottomLeft(outline.getExtent());
    outline.translate(offset - origin[0], offset - origin[1]);
    return outline;
  };
})();

const styleCache = {};

const vector = new VectorLayer({
  source: new VectorSource({
    url: 'data/kml/2012_Earthquakes_Mag5.kml',
    format: new KML({
      extractStyles: false,
    }),
  }),
  style: function (feature) {
    const magnitude = feature.get('magnitude');
    let style = styleCache[magnitude];
    if (!style) {
      const scale = 1 + 4 * (magnitude - 5);
      const lineWidth = 2;
      const outline = getSymbolOutline(scale, Math.ceil(lineWidth / 2));
      const canvas = document.createElement('canvas');
      const vectorContext = toContext(canvas.getContext('2d'), {
        size: getTopRight(outline.getExtent()).map((n) =>
          Math.ceil(n + lineWidth / 2),
        ),
        pixelRatio: DEVICE_PIXEL_RATIO,
      });
      vectorContext.setStyle(
        new Style({
          fill: new Fill({color: 'rgba(255, 153, 0, 0.4)'}),
          stroke: new Stroke({
            color: 'rgba(255, 204, 0, 0.2)',
            width: 2,
          }),
        }),
      );
      vectorContext.drawGeometry(outline);
      style = new Style({
        image: new Icon({
          img: canvas,
          scale: 1 / DEVICE_PIXEL_RATIO,
        }),
      });
      styleCache[magnitude] = style;
    }
    return style;
  },
});
// 2012_Earthquakes_Mag5.kml 将每次地震的震级存储在每个
// Placemark 中一个不符合标准的 <magnitude> 标签里。我们改为从
// Placemark 的名称中提取它。
function parseMagnitudeFromName(name) {
  return parseFloat(name.substr(2));
}
vector.getSource().on('featuresloadend', function (evt) {
  evt.features.forEach((f) => {
    f.set('magnitude', parseMagnitudeFromName(f.get('name')), true);
  });
});

const raster = new TileLayer({
  source: new StadiaMaps({
    layer: 'stamen_toner',
  }),
});

const map = new Map({
  layers: [raster, vector],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>使用自定义符号的地震</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>

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