Sunday 24 May 2015

javascript - Sketch event in Openlayers 3 drawing interaction


For drawing Polygon in OpenLayers 2 we could use as follow:


function drawEnd(){
...

}

function putPoint(){
...
}

function sketchModified(){
...
}


function cancel(){
...
}

var callBackParams = {
"done": drawEnd,
"point": putPoint,
"modify": sketchModified,
"cancel": cancel
}


var drawCrtl = new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Polygon, {callbacks: callBackParams});
map.addControls([drawCrtl]);
drawCrtl.activate();

When we put point to drawing the polygon, the system call putPoint function. When mouse move over the map, it call sketchModified function. I want to use these two Event in OpenLayers 3. I define my layer as follow:


var source = new ol.source.Vector({wrapX: false});

var vector = new ol.layer.Vector({
source: source

});
draw = new ol.interaction.Draw({
source: source,
type: 'Polygon'
});

drawStart = function(){
console.log("Salam Bar Mahdi");
}
drawEnd = function(){

console.log("Ya Mahdi");
}

draw.on('drawstart', drawStart);
draw.on('drawend', drawEnd);
var map = new ol.Map({
interactions: ol.interaction.defaults().extend([select, modify, draw]),
target: 'map',
layers: [
new ol.layer.Tile({

title: "Global Imagery",
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/world/wms?service=WMS',
params: {LAYERS: 'world:worldRaster', VERSION: '1.1.1'}
})
}),
vector
],
view: new ol.View({
projection: 'EPSG:4326',

center: [0, 0],
zoom: 4
})
});

But in Openlayers 3 I saw only drawEnd and DrawStart Event.


How Can I do?



Answer



OpenLayers v3.5.0 does not easily support the feature you're looking for, but there is a feature currently in development that you can use.


On ol.interaction.Draw, you can specify an ol.interaction.DrawGeometryFunctionType function to handle updates to the current geometry.



An example I've written up is shown below:


var geometryFunction = function (c, g) {
if (goog.isDef(g)) {
g.setCoordinates(c);
} else {
g = new ol.geom.Polygon(c);
}

if (c[0].length > ct) {
console.log('mouse click coord : ' + c[0][c[0].length - 1]);

ct = c[0].length;
} else {
console.log('mouse move coord : ' + c[0][c[0].length - 1]);
}

return g;
}

This is pretty much what the default geometryFunction function does, without the new point identification and console logging.


A fully functional example is here: http://jsfiddle.net/1a948faa/2/



Note the following caveats:



  • You will have to implement a separate function, or case for different geometry types.

  • The code is currently still in development and is thus not stable. In addition it is subject to change at any time.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...