简体   繁体   中英

Polygon Selection OpenLayers 3

How can you select features with a polygon draw? It can be done with a square box select as per the examples.

I'm wondering if there's a way to trigger an event after creating the polygon to go and check for intersections with it and other features. In my case I'm trying to capture datapoints.

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

    var selectedFeatures = select.getFeatures();

    // a DragBox interaction used to select features by drawing boxes
    var dragBox = new ol.interaction.DragBox({
        condition: ol.events.condition.platformModifierKeyOnly
    });

    map.addInteraction(dragBox);

    var infoBox = document.getElementById('info');

    dragBox.on('boxend', function() {
        // features that intersect the box are added to the collection of
        // selected features, and their names are displayed in the "info"
        // div
        var info = [];
        var extent = dragBox.getGeometry().getExtent();
        vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
            selectedFeatures.push(feature);
            info.push(feature.get('name'));
        });
        if (info.length > 0) {
            infoBox.innerHTML = info.join(', ');
        }
    });

    // clear selection when drawing a new box and when clicking on the map
    dragBox.on('boxstart', function() {
        selectedFeatures.clear();
        infoBox.innerHTML = ' ';
    });
    map.on('click', function() {
        selectedFeatures.clear();
        infoBox.innerHTML = ' ';
    });

Is this possible in open layers 3 ?

For such actions you need to use either JSTS topology library or TURF.js lib. In my personal opinion JSTS is much more complete and elegand solution. Get some info here . For the time being, author is making changes and is about to release an official ol3 compatitable version so keep informed.

I ll give you an example using an older version of JSTS which does the job. (check the external sources of the provided fiddle to verify the JSTS lib files you need to load). If you have the time check if there are any new links for the latest JSTS version and let us know if you have any news.

here is the logic:

  1. Create 3 vector layers. One for the layer you want to query from, one for placing your free hand drawing and one more to place your highlights.

  2. Create a draw interaction and attach a 'drawend' event on it.

  3. Use the JSTS to find geometries intersecting with the digitised geometry.

So here is your code and a fiddle to make your life easier.

var waterAreasVecSource = new ol.source.Vector({
    loader: function (extent) {
        $.ajax('http://demo.opengeo.org/geoserver/wfs', {
            type: 'GET',
            data: {
                service: 'WFS',
                version: '1.1.0',
                request: 'GetFeature',
                typename: 'water_areas',
                srsname: 'EPSG:3857',
                bbox: extent.join(',') + ',EPSG:3857'
            }
        }).done(loadFeatures)
            .fail(function () {
        alert("fail loading layer!!!")
        });
    },
    strategy: ol.loadingstrategy.bbox
});

function loadFeatures(response) {
    formatWFS = new ol.format.WFS(),
    waterAreasVecSource.addFeatures(formatWFS.readFeatures(response));
}

var waterAreasVector = new ol.layer.Vector({
    source: waterAreasVecSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 255, 1.0)',
            width: 2
        })
    })
});
var raster = new ol.layer.Tile({
  source: new ol.source.OSM({})
});

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

var myDrawVector = new ol.layer.Vector({
  source: myDrawSource,
  style: new ol.style.Style({
    fill: new ol.style.Fill({
      color: 'rgba(255, 255, 255, 0.5)'
    }),
    stroke: new ol.style.Stroke({
      color: '#ffcc33',
      width: 2
    }),
    image: new ol.style.Circle({
      radius: 7,
      fill: new ol.style.Fill({
        color: '#ffcc33'
      })
    })
  })
});

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

var mySelectionsVector = new ol.layer.Vector({
  source: mySelectionsSource,
  style: new ol.style.Style({
    fill: new ol.style.Fill({
      color: 'rgba(255, 0, 0, 0.5)'
    }),
    stroke: new ol.style.Stroke({
      color: 'rgba(255, 0, 0, 1)',
      width: 2
    }),
    image: new ol.style.Circle({
      radius: 7,
      fill: new ol.style.Fill({
        color: '#ffcc33'
      })
    })
  })
});

var map = new ol.Map({
  layers: [raster, myDrawVector,waterAreasVector,mySelectionsVector],
  target: 'map',
  view: new ol.View({
    center: [-8908887.277395891, 5381918.072437216],
    maxZoom: 19,
    zoom: 12
  })
});


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

map.addInteraction(draw);

draw.on('drawend',function(e){
myDrawSource.clear();
mySelectionsSource.clear();
var extent = e.feature.getGeometry().getExtent();
var geomA = e.feature.getGeometry();
waterAreasVecSource.forEachFeatureInExtent(extent,function(aa){
console.log("forEachFeatureInExtent",aa.getGeometry());
if (polyIntersectsPoly(geomA,aa.getGeometry()) === true){
mySelectionsSource.addFeature(aa);
}
});
});



/**
* check whether the supplied polygons have any spatial interaction
* @{ol.geometry.Polygon} polygeomA 
* @{ol.geometry.Polygon} polygeomB 
* @returns {Boolean} true||false
*/
function polyIntersectsPoly(polygeomA, polygeomB) {
 var geomA = new jsts.io.GeoJSONReader().read(new ol.format.GeoJSON().writeFeatureObject(
        new ol.Feature({
            geometry: polygeomA
       })
   )
   ).geometry;
var geomB = new jsts.io.GeoJSONReader().read(new ol.format.GeoJSON().writeFeatureObject(
        new ol.Feature({
            geometry: polygeomB
        })
    )
    ).geometry;
return geomA.intersects(geomB);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM