forked from openlayers/openlayers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdraw-shapes.js
87 lines (79 loc) · 2.37 KB
/
draw-shapes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import Draw, {
createBox,
createRegularPolygon,
} from '../src/ol/interaction/Draw.js';
import Map from '../src/ol/Map.js';
import Polygon from '../src/ol/geom/Polygon.js';
import View from '../src/ol/View.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
const raster = new TileLayer({
source: new OSM(),
});
const source = new VectorSource({wrapX: false});
const vector = new VectorLayer({
source: source,
});
const map = new Map({
layers: [raster, vector],
target: 'map',
view: new View({
center: [-11000000, 4600000],
zoom: 4,
}),
});
const typeSelect = document.getElementById('type');
let draw; // global so we can remove it later
function addInteraction() {
let value = typeSelect.value;
if (value !== 'None') {
let geometryFunction;
if (value === 'Square') {
value = 'Circle';
geometryFunction = createRegularPolygon(4);
} else if (value === 'Box') {
value = 'Circle';
geometryFunction = createBox();
} else if (value === 'Star') {
value = 'Circle';
geometryFunction = function (coordinates, geometry) {
const center = coordinates[0];
const last = coordinates[1];
const dx = center[0] - last[0];
const dy = center[1] - last[1];
const radius = Math.sqrt(dx * dx + dy * dy);
const rotation = Math.atan2(dy, dx);
const newCoordinates = [];
const numPoints = 12;
for (let i = 0; i < numPoints; ++i) {
const angle = rotation + (i * 2 * Math.PI) / numPoints;
const fraction = i % 2 === 0 ? 1 : 0.5;
const offsetX = radius * fraction * Math.cos(angle);
const offsetY = radius * fraction * Math.sin(angle);
newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
}
newCoordinates.push(newCoordinates[0].slice());
if (!geometry) {
geometry = new Polygon([newCoordinates]);
} else {
geometry.setCoordinates([newCoordinates]);
}
return geometry;
};
}
draw = new Draw({
source: source,
type: value,
geometryFunction: geometryFunction,
});
map.addInteraction(draw);
}
}
/**
* Handle change event.
*/
typeSelect.onchange = function () {
map.removeInteraction(draw);
addInteraction();
};
addInteraction();