more cowbell
more cowbell

Reputation: 101

How to drag features in Open Layers 3?

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)

Upvotes: 7

Views: 8881

Answers (3)

Shaunak
Shaunak

Reputation: 18018

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);

Upvotes: 11

MSS
MSS

Reputation: 3860

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);

Upvotes: -1

tsauerwein
tsauerwein

Reputation: 6011

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

Upvotes: -1

Related Questions