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).
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Draw from 'ol/interaction/Draw.js';
import Modify from 'ol/interaction/Modify.js';
import Select from 'ol/interaction/Select.js';
import Snap from 'ol/interaction/Snap.js';
import VectorLayer from 'ol/layer/Vector.js';
import {useGeographic} from 'ol/proj.js';
import VectorSource from 'ol/source/Vector.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();
<!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>
{
"name": "edit-geographic",
"dependencies": {
"ol": "10.5.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}