Question

I've created a site link text using the api produced by the Ordnance Survey (I think this is called OpenSpace) which is based on OpenLayers. I've got it so you can click on the map to add a marker and I want to then be able to click on the markers and drag it around the map. Is there a simple way to do this using either the OpenSpace or OpenLayers apis.

No correct solution

OTHER TIPS

The OpenLayers api allows you to add Markers and Features to the map. If you add Features rather than Markers you can make them draggable by adding the following code.

var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer");
var osMap = new OpenSpace.Map('map');
osMap.addLayer(vectorLayer);

var modifyFeaturesControl = new OpenLayers.Control.ModifyFeature(vectorLayer);
modifyFeaturesControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE;
osMap.addControl(modifyFeaturesControl);
modifyFeaturesControl.activate();

This will allow you to drag features around a map. If you want to add custom behavior when feature's are dragged you can register listeners on the vectorLayer. For example to register a listener when features are modifed (i.e. dragged and released) you need to use the following code.

vectorLayer.events.register('featuremodified', vectorLayer, function(feature) {
   //custom behavior
});

For a full list of the events that can be listened to see the OpenLayers api doc OpenLayers api doc

As easier way to do this is by using the openlayer drag control, which takes a vector layer as a target.

Assuming a vector layer containing icons (this is prefered to markers, which the developers of OL discourage using), called vectors, you can simply do:

var drag=new OpenLayers.Control.DragFeature(vectors);

map.addControl(drag);
drag.activate();

The other advantage of using the drag control is that you can hook into various callbacks, which return the feature and pixel position, such as onStart and onDrag. eg,

var drag=new OpenLayers.Control.DragFeature(vectors,{    
     'onDrag':function(feature, pixel){
           console.log(pixel.x);//this can be used to do something else, such as move another feature
     }
});

See http://trac.osgeo.org/openlayers/browser/trunk/openlayers/lib/OpenLayers/Control/DragFeature.js for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top