Edit

Immediate Rendering (Geographic)

immediate1 geographic4

Using the immediate rendering API with geometries in geographic coordinates.

This example uses the "immediate" rendering API with geometries in geographic coordinates. The immediate rendering API lets you draw styled geometries without adding them to a layer first. Use the getVectorContext function to create a rendering context from a render event. Using the context.drawGeometry() and context.setStyle() methods on this rendering context, you can draw any geometry on each render frame. The useGeographic function is used in this example so that geometries can be in geographic coordinates.

main.js
import StadiaMaps from 'ol/source/StadiaMaps.js';
import TileLayer from 'ol/layer/Tile.js';
import {Circle, Fill, Style} from 'ol/style.js';
import {Map, View} from 'ol/index.js';
import {Point} from 'ol/geom.js';
import {getVectorContext} from 'ol/render.js';
import {upAndDown} from 'ol/easing.js';
import {useGeographic} from 'ol/proj.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
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Immediate Rendering (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
{
  "name": "immediate-geographic",
  "dependencies": {
    "ol": "9.1.0"
  },
  "devDependencies": {
    "vite": "^3.2.3"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}