Convenience function for drawing box-shaped polygons

This commit is contained in:
Tim Schaub
2016-10-16 15:49:13 -06:00
parent 92583542eb
commit 9b12cac5c6
2 changed files with 60 additions and 0 deletions

View File

@@ -2,6 +2,7 @@ goog.provide('ol.interaction.Draw');
goog.require('ol');
goog.require('ol.events');
goog.require('ol.extent');
goog.require('ol.events.Event');
goog.require('ol.Feature');
goog.require('ol.MapBrowserEvent.EventType');
@@ -766,6 +767,36 @@ ol.interaction.Draw.createRegularPolygon = function(opt_sides, opt_angle) {
};
/**
* Create a `geometryFunction` that will create a box-shaped polygon (aligned
* with the coordinate system axes). Use this with the draw interaction and
* `type: 'Circle'` to return a box instead of a circle geometry.
* @return {ol.DrawGeometryFunctionType} Function that draws a box-shaped polygon.
* @api
*/
ol.interaction.Draw.createBox = function() {
return (
/**
* @param {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>} coordinates
* @param {ol.geom.SimpleGeometry=} opt_geometry
* @return {ol.geom.SimpleGeometry}
*/
function(coordinates, opt_geometry) {
var extent = ol.extent.boundingExtent(coordinates);
var geometry = opt_geometry || new ol.geom.Polygon(null);
geometry.setCoordinates([[
ol.extent.getBottomLeft(extent),
ol.extent.getBottomRight(extent),
ol.extent.getTopRight(extent),
ol.extent.getTopLeft(extent),
ol.extent.getBottomLeft(extent)
]]);
return geometry;
}
);
};
/**
* Get the drawing mode. The mode for mult-part geometries is the same as for
* their single-part cousins.

View File

@@ -897,6 +897,35 @@ describe('ol.interaction.Draw', function() {
});
});
describe('ol.interaction.Draw.createBox', function() {
it('creates a box-shaped polygon in Circle mode', function() {
var draw = new ol.interaction.Draw({
source: source,
type: 'Circle',
geometryFunction: ol.interaction.Draw.createBox()
});
map.addInteraction(draw);
// first point
simulateEvent('pointermove', 0, 0);
simulateEvent('pointerdown', 0, 0);
simulateEvent('pointerup', 0, 0);
// finish on second point
simulateEvent('pointermove', 20, 20);
simulateEvent('pointerdown', 20, 20);
simulateEvent('pointerup', 20, 20);
var features = source.getFeatures();
var geometry = features[0].getGeometry();
expect(geometry).to.be.a(ol.geom.Polygon);
var coordinates = geometry.getCoordinates();
expect(coordinates[0]).to.have.length(5);
expect(geometry.getArea()).to.equal(400);
expect(geometry.getExtent()).to.eql([0, -20, 20, 0]);
});
});
describe('extend an existing feature', function() {
var draw;
var feature;