Skip to content

Immediate 渲染 (Geographic) ​

Immediate 渲染 (Geographic)示例。 immediate 地理坐标

本示例在地理坐标系下使用"immediate"(立即)渲染 API 绘制几何图形。立即渲染 API 允许你直接绘制带样式的几何图形,而无需先将它们添加到图层中。使用 getVectorContext 函数可以从渲染事件创建一个渲染上下文。在该渲染上下文上调用 context.drawGeometry() 和 context.setStyle() 方法,就可以在每一渲染帧上绘制任意几何图形。本示例使用了 useGeographic 函数,因此几何图形可以使用地理坐标。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {upAndDown} from 'ol/easing.js';
import Point from 'ol/geom/Point.js';
import TileLayer from 'ol/layer/Tile.js';
import {useGeographic} from 'ol/proj.js';
import {getVectorContext} from 'ol/render.js';
import StadiaMaps from 'ol/source/StadiaMaps.js';
import Circle from 'ol/style/Circle.js';
import Fill from 'ol/style/Fill.js';
import Style from 'ol/style/Style.js';

useGeographic();

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

const map = new Map({
  layers: [layer],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

const image = new Circle({
  radius: 8,
  fill: new Fill({color: 'rgb(255, 153, 0)'}),
});

const style = new Style({
  image: image,
});

const n = 1000;
const geometries = new Array(n);

for (let i = 0; i < n; ++i) {
  const lon = 360 * Math.random() - 180;
  const lat = 180 * Math.random() - 90;
  geometries[i] = new Point([lon, lat]);
}

layer.on('postrender', function (event) {
  const vectorContext = getVectorContext(event);

  for (let i = 0; i < n; ++i) {
    const importance = upAndDown(Math.pow((n - i) / n, 0.15));
    if (importance < 0.1) {
      continue;
    }
    image.setOpacity(importance);
    image.setScale(importance);
    vectorContext.setStyle(style);
    vectorContext.drawGeometry(geometries[i]);
  }

  const lon = 360 * Math.random() - 180;
  const lat = 180 * Math.random() - 90;
  geometries.push(new Point([lon, lat]));
  geometries.shift();
  map.render();
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Immediate 渲染 (Geographic)</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": "immediate-geographic",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}