Edit

Geographic Editing

geographic4

Editing geometries with geographic coordinates.

Calling the useGeographic function in the 'ol/proj' module makes it so the map view uses geographic coordinates (even if the view projection is not geographic).

main.js
import GeoJSON from 'ol/format/GeoJSON.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import {Draw, Modify, Select, Snap} from 'ol/interaction.js';
import {Map, View} from 'ol/index.js';
import {useGeographic} from 'ol/proj.js';

useGeographic();

const source = new VectorSource({
  url: 'https://openlayers.org/data/vector/us-states.json',
  format: new GeoJSON(),
});

const map = new Map({
  target: 'map',
  layers: [
    new VectorLayer({
      background: 'white',
      source: source,
    }),
  ],
  view: new View({
    center: [-100, 38.5],
    zoom: 4,
  }),
});

const select = new Select();

const modify = new Modify({
  features: select.getFeatures(),
});

const draw = new Draw({
  type: 'Polygon',
  source: source,
});

const snap = new Snap({
  source: source,
});

function removeInteractions() {
  map.removeInteraction(modify);
  map.removeInteraction(select);
  map.removeInteraction(draw);
  map.removeInteraction(select);
}

const mode = document.getElementById('mode');
function onChange() {
  removeInteractions();
  switch (mode.value) {
    case 'draw': {
      map.addInteraction(draw);
      map.addInteraction(snap);
      break;
    }
    case 'modify': {
      map.addInteraction(select);
      map.addInteraction(modify);
      map.addInteraction(snap);
      break;
    }
    default: {
      // pass
    }
  }
}
mode.addEventListener('change', onChange);
onChange();
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Geographic Editing</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>
    <select id="mode">
      <option value="modify">select a feature to modify</option>
      <option value="draw">draw new features</option>
    </select>

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