[GIS] Dragging a feature in OpenLayers 3

drag and dropfeaturesjavascriptopenlayersopenlayers-2

I'm trying to replicate something that was fairly easy in OpenLayers 2 in OpenLayers 3, which is: dragging an existing feature to a new location on the map.

In OpenLayers 2 I just added a DragFeature control to my map like this:

this.mapRasterDragFeature = new OpenLayers.Control.DragFeature(_self.rasterVectorSource,
     {'onComplete': function(e) { console.log(e);}});
this.mapRaster.addControl(_self.mapRasterDragFeature);
this.mapRasterDragFeature.activate();

But this control seems to have disappeared in OpenLayers 3. I've searched far and wide in the documentation for the new way to this, but I can't seem to find it. I hope I'm overlooking something.

I'm adding the feature through a click event on the map like this:

this.mapRaster.on('singleclick',function(e){
    var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(e.coordinate),
    });
    iconFeature.setStyle(_self.iconStyle);
    _self.rasterVectorSource.addFeatures([iconFeature]);
});

All I've found looking like a drag interaction is ol.interaction.DragAndDrop(), but I think it does something different than just dragging and dropping a feature…

Can someone help me out on this one?

Best Answer

You will need to add a new interaction. Assuming that...

this.mapRaster = ol.Map

This should work

this.mapRaster.on('singleclick',function(e){
    var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(e.coordinate),
    });
    iconFeature.setStyle(_self.iconStyle);
    _self.rasterVectorSource.addFeatures([iconFeature]);

Make the feature moveable

    var modify = new ol.interaction.Modify({
        features: new ol.Collection([iconFeature])
    });

Let me know when the feature is moving

    iconFeature.on('change',function(){
        console.log('Feature Moved To:' + this.getGeometry().getCoordinates());
    },iconFeature);

Then add the Modify Interaction

    this.mapRaster.addInteraction(modify);

});