After introducing the goal, we should do the following:
osm_default and map variables.ol.interaction.DragBox, as follows:var dragBoxInteraction = new ol.interaction.DragBox({
condition: ol.events.condition.shiftKeyOnly,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
})
})
});DragRotateAndZoom, deactivate DragZoom, and add the new interaction in the interactions parameter within ol.Map, as follows:interactions: ol.interaction.defaults({
shiftDragZoom: false
}).extend([dragBoxInteraction]),dragBoxInteraction and map declarations:dragBoxInteraction.on('boxend', function(e) {
var format = new ol.format.GeoJSON();
var geom = e.target.getGeometry();
geom.transform('EPSG:3857', 'EPSG:4326');
var feature = new ol.Feature({
geometry: geom
});
var obj = format.writeFeatures([feature]);
console.log(JSON.stringify(obj));
});In the first part, you should be able to draw the rectangle, but no events fired then like with the DragZoom for example. We chose to play with all the available options.
We set the condition to be able to activate the behavior only with the Shift key using ol.events.condition.shiftKeyOnly and changed the style to make a red border with 1 pixel's width.
We added the new interaction but disabled the other, which also uses ol.events.condition.shiftKeyOnly.
Finally, we reused the event listener to catch when the rectangle drawing ends with boxend.
Within this event, we manipulated the returned geometry ol.geometry.Polygon to change it projection and reuse it into ol.Feature. By providing this feature with the writeFeatures method of a new ol.format.GeoJSON, we were able to make the GeoJSON object and converted it into a string.
As a reminder, in the following table, you will find the expected optional parameters (and experimental) for the interaction:
|
Name |
Type |
Description |
|---|---|---|
|
|
|
This is a function that takes |
|
|
|
This is a style for the box. |
After this last assignment for the book, it's time for revision.
Let's look at a few questions to see what we understood during the chapter:
Q1. In a context where we want to query a WMS, what components and methods would be required for this?
ol.Map.ol.layer.Tile.ol.source.ImageWMS.ol.layer.Vector.ol.source.TileWMS.Q2. What will happen if we use the addCondition property value ol.interaction.condition.onlyAltKey to build ol.interaction.Select?
Q3. We want to make a style change. When selecting, what type is required in the option style of ol.layer.Vector?
ol.style.Style.ol.style.Stroke.ol.style.Fill.ol.style.Style.Q4. What is(are) the condition(s) not present by default in the available conditions when using interactions :
ol.events.condition.neverShift.ol.events.condition.never.ol.events.condition.shiftAlways.ol.events.condition.noModifierKey.ol.events.condition.shiftKeyOnly.