How to drag features in Open Layers 3?
Asked Answered
F

3

7

In the OL3 examples I can drag objects and drop on the map, but I want to move/resize/rotate things that are already on the map like ol.geom.Point and other ol.geom objects. What is the OL3 way do do this?

Example in OL2:

OpenLayers.Control.DragFeature(layer)
Frei answered 7/7, 2014 at 7:27 Comment(1)
Very good question. It doesn't seem to have been implemented yet.Gatto
T
11

Not sure why the example on OL3 website is so complicated. Dragging vector objects can be easily achieved using new ol.interaction.Modify.

enter image description here

Here is a simpler working example: jsFiddle

In short, if you marker was:

var pointFeature = new ol.Feature(new ol.geom.Point([0, 0]));

You can define modify interaction as :

var dragInteraction = new ol.interaction.Modify({
    features: new ol.Collection([pointFeature]),
    style: null
});

map.addInteraction(dragInteraction);

You can then get a event for getting the new location of marker after drag like so:

pointFeature.on('change',function(){
            console.log('Feature Moved To:' + this.getGeometry().getCoordinates());
},pointFeature);
There answered 18/8, 2015 at 20:56 Comment(2)
yes and it seams the translate interaction works but slightly different there is one of them that steal works on version 4 too. tsauerwein.github.io/ol3/animation-flights/examples/…Mccrea
Works perfectly! Great job. Thank youGodevil
B
-1

Take a look at the modify interaction (example). Though rotation is not yet supported.

Beaubeauchamp answered 21/7, 2014 at 14:32 Comment(0)
M
-1

I have create a simple lib that add drag interaction to openlayers 4 by slightly changing this official example: https://openlayers.org/en/latest/examples/custom-interactions.htm

you can find the lib here : https://gist.github.com/kingofnull/0ad644be69d8dd43c05721022ca5c3a5

and you should simply add it this way:

var map = new ol.Map({
  interactions: ol.interaction.defaults().extend([new ol.interaction.Drag(),])
});

Update

I test the translate and it works in openlayer 4 and there is no need for a custom interaction. keep it in mind if you going to combine it with modify interaction you should add it before modify. here is my final code:

var map = new ol.Map({...});
var featureDrager = new ol.interaction.Translate();
var modify = new ol.interaction.Modify({...});
map.addInteraction(featureDrager);
map.addInteraction(modify);
Mccrea answered 13/2, 2018 at 7:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.