JSFiddle - React, Tailwind, and code Playground
by Paolo Favero
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/ol.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ol.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scale Box</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<form>
<label for="type">Geometry type </label>
<select id="type">
<option value="draw">draw rects</option>
<option value="modify">modify rects</option>
</select>
</form>
</body>
</html>
JavaScript
import Map from 'ol/Map';
import View from 'ol/View';
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
import {Draw, Modify, Translate} from 'ol/interaction';
import {
createBox
} from 'ol/interaction/Draw';
import {MultiPoint} from 'ol/geom';
import {OSM, Vector as VectorSource} from 'ol/source';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {getCenter, getHeight, getWidth} from 'ol/extent';
import {
never,
platformModifierKeyOnly,
primaryAction,
} from 'ol/events/condition';
// add map
const source = new VectorSource();
const style = new Style({
geometry: function (feature) {
const modifyGeometry = feature.get('modifyGeometry');
return modifyGeometry ? modifyGeometry.geometry : feature.getGeometry();
},
fill: new Fill({
color: 'rgba(255, 255, 255, 0.6)',
}),
stroke: new Stroke({
color: '#ffcc33',
width: 2,
})
});
const vector = new VectorLayer({
source: source,
style: function (feature) {
return style;
},
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
vector
],
target: 'map',
view: new View({
center: [1800000, 6400000],
zoom: 5,
}),
});
// add draw interaction
const draw = new Draw({
source: source,
type: 'Circle',
geometryFunction: createBox()
});
map.addInteraction(draw);
// add modify interaction
const defaultModifyStyle = new Modify({source: source}).getOverlay().getStyleFunction();
const modify = new Modify({
source: source,
deleteCondition: never,
insertVertexCondition: never,
style: function (feature) {
source.getFeatures().forEach(function (modifyFeature) {
const modifyGeometry = modifyFeature.get('modifyGeometry');
if (modifyGeometry) {
const point = feature.getGeometry().getCoordinates();
console.log(point);
let modifyPoint = modifyGeometry.point;
if (!modifyPoint) {
// save the initial geometry and vertex position
modifyPoint = point;
modifyGeometry.point =...