Files
openlayers/examples/draw-shapes.js
Tim Schaub ad62739a6e Use blocked scoped variables
In addition to using const and let, this also upgrades our linter config and removes lint (mostly whitespace).
2018-01-12 00:50:30 -07:00

87 lines
2.4 KiB
JavaScript

import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import Polygon from '../src/ol/geom/Polygon.js';
import Draw from '../src/ol/interaction/Draw.js';
import TileLayer from '../src/ol/layer/Tile.js';
import VectorLayer from '../src/ol/layer/Vector.js';
import OSM from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.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 = Draw.createRegularPolygon(4);
} else if (value === 'Box') {
value = 'Circle';
geometryFunction = Draw.createBox();
} else if (value === 'Star') {
value = 'Circle';
geometryFunction = function(coordinates, geometry) {
if (!geometry) {
geometry = new Polygon(null);
}
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());
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();