Search code examples
overlayopenlayers-3drawrectangleol3-google-maps

Openlayer 3 rectangular selection


I have added some overlays in openlayer 3.Is it possible that if i click on ctrl+mouse left click and drag mouse to select a rectangular area on map and i need to get the overlays listed in that particular area?


Solution

  • Yes, it is possible with the DragBox element.

    This way you declare the element:

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

    And you can add it as interaction to your already existing map:

    map.addInteraction(dragBox);
    

    If you want to add some behavior, it is possible to call the events boxstart and boxend:

    dragBox.on('boxstart', function() {
        // Your stuff when the box starts being drawn
    });
    dragBox.on('boxend', function() {
        // Your stuff when the box is already drawn
    });
    

    You will find more information in the OpenLayers 3 API: http://openlayers.org/en/latest/apidoc/ol.interaction.DragBox.html

    You can also take a look at the Box Selection example here: https://openlayers.org/en/latest/examples/box-selection.html