1

I would like to make a selection with DragBox interaction and get the geometry type to Multipolygon.

Right now I'm getting a Polygon type back :

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

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        new ol.layer.Vector({
            source: source
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([-3, 48]),
        zoom: 7
    }), 
});

var select = new ol.interaction.Select();

var dragBox = new ol.interaction.DragBox({
    condition: ol.events.condition.platformModifierKeyOnly });

dragBox.on('boxend', function() {
    var geom = dragBox.getGeometry();
    var format = new ol.format.WKT();
    var wktRepresentation  = format.writeGeometry(geom);

    console.log("wktRepresentation: " + wktRepresentation); 
});

Can someone help me?

1

The reason for that is because dragBox.getGeometry() returns bbox geometry. You should get geometry from features that intersect with bbox. Lets suppose that geojson file that is loaded have both polygon and multipolygon geometry type. The function in this case for 'bboxend' event is as follow.

  var selectedMultiPolygon;
dragBox.on('boxend', function() {
    selectedMultiPolygon = new ol.geom.MultiPolygon();
    var extent = dragBox.getGeometry().getExtent();
    source.forEachFeatureIntersectingExtent(extent,
        function(feature) {
            //check geometry type
            if (feature.getGeometry().getType() == 'MultiPolygon') {
                var polygonsArray = feature.getGeometry().getPolygons();
                for (i = 0; i < polygonsArray.length; i++) {
                    selectedMultiPolygon.appendPolygon(polygonsArray[i]);
                }
            } else if (feature.getGeometry().getType() == 'Polygon') {

            selectedMultiPolygon.appendPolygon(feature.getGeometry());
        }

        selectedFeatures.push(feature);

    });
console.log(selectedMultiPolygon);
});

Here is the fiddle: https://jsfiddle.net/v3yqf78L/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.