Drag & Drop items on openlayer map

This article will help to implement drag & drop features in openlayer.

To load map first we need one div

<div id=”map” class=”map” ondrop=”drop(event)” ondragover=”allowDrop(event)”></div>

Also we would also be needing items to drop on map.

<span id=”drag1" style=”cursor: move;” src=”img_logo.gif” draggable=”true” ondragstart=”drag(event)” width=”336" height=”69"> Drag Me 1 </span>

<span id=”drag2" style=”cursor: move;” src=”img_logo.gif” draggable=”true” ondragstart=”drag(event)” width=”336" height=”69"> Drag Me 2 </span>

Above code is self explanatory. Below is our drop function.

function drop(ev) {

ev.preventDefault();

lastDropLocation[“x”] = ev.pageX;

lastDropLocation[“y”] = ev.pageY;

var pixel = [ev.pageX, ev.pageY];

var point = map.getCoordinateFromPixel(pixel);

var pointArray = ol.proj.transform(point, ‘EPSG:3857’, ‘EPSG:4326’)

var lon = pointArray[0];

var lat = pointArray[1];

var marker = new ol.Feature({

geometry: new ol.geom.Point(

ol.proj.fromLonLat([lon, lat])

), // Cordinates of Baripada Town

});

marker.setStyle(new ol.style.Style({

image: new ol.style.Icon( ({

src: ‘https://cdn4.iconfinder.com/data/icons/small-n-flat/24/user-alt-64.png'

}))

}));

var vectorSource = new ol.source.Vector({

features: [marker]

});

var markerVectorLayer = new ol.layer.Vector({

source: vectorSource,

});

map.addLayer(markerVectorLayer);

var translate1 = new ol.interaction.Translate({

features: new ol.Collection([marker])

});

map.addInteraction(translate1);

map.on(‘singleclick’, function (evt) {

console.log(evt.coordinate);

});

}

Please get the full source code from below location

https://github.com/deepuRai/Openlayer_drag_drop

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store