-4

I want to create a draggable icon on OpenLayers maps for locations.

With the code below, I can put an icon (using a PNG image) on the map, but it is not draggable. How can I achieve that?

<html>
<body>
<div id="mapdiv"></div>
  <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
  <script>
        map = new OpenLayers.Map("mapdiv");
        map.addLayer(new OpenLayers.Layer.OSM());

        var lonLat = new OpenLayers.LonLat( 72.91152, 19.11186 )
          .transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            map.getProjectionObject() // to Spherical Mercator Projection
          );

        var zoom=16;
        var osm = new OpenLayers.Layer.OSM();
        var vectors = new OpenLayers.Layer.Vector("Vector Layer");
        map.addLayers([osm, vectors]);

        var markers = new OpenLayers.Layer.Markers( "Markers" );
        map.addLayer(markers);

        var size = new OpenLayers.Size(25,37);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        mymarker = new OpenLayers.Icon('marker-icon.png', size, offset);
        markers.addMarker(new OpenLayers.Marker(lonLat, mymarker));

    var point = new OpenLayers.Geometry.Point(lonLat.lon,lonLat.lat);
    vectors.addFeatures([new OpenLayers.Feature.Vector(point)]);
    drag = new OpenLayers.Control.DragFeature(vectors, {autoActivate: true});
    map.addControl(drag);
    map.setCenter (lonLat, zoom);
    </script>
</body></html>
legoscia
  • 39,593
  • 22
  • 116
  • 167
Prem J
  • 1
  • 3
  • after running the above code the icon appears on map. and i want that icon to be draggable. thats it – Prem J Aug 07 '19 at 06:42

1 Answers1

2

The DragFeature control works on vector features. If you want to drag an icon you will need to style the feature as an icon. Something like this but without access to your image I can't be sure of the size and offsets you will need

vectors.addFeatures([new OpenLayers.Feature.Vector(point, null, {
    externalGraphic: 'marker-icon.png',
    graphicWidth: 25,
    graphicYOffset: -30
})]);
Mike
  • 16,042
  • 2
  • 14
  • 30