views:

26

answers:

1

I'm developing a Google Map API v2 app, where markers are loaded from a database. These markers can then be dragged to a new location by a user and saved to the database.

I'm adding these markers as draggable, however I don't just want the users to be able to drag them accidentally. So I have added a button to enable the dragging and then press again to disable it.

Only problem is I'm not sure how I can toggle the ability to drag the markers without reloading them again, as there could be a few hundred markers on the map and may take some time.

Any ideas how I could achieve this?

Thanks

A: 

That should be very easy to do. First you need to keep a reference to all your markers. Then to toggle the dragging behaviour, you can simply iterate through your markers and call the enableDragging() or the disableDragging() method on each marker.

For this to work, your markers will have to be initialized with the GMarkerOptions.draggable option set to true, but I assume you are already doing this.

Here's a fully working example:

<!DOCTYPE html>
<html> 
<head>
   <script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=false" 
           type="text/javascript"></script>
</head> 
<body onunload="GUnload()">
   <div id="map" style="width: 400px; height: 300px"></div> 

   <input type="button" value="Toggle Drag" onclick="toggleDrag()">

   <script type="text/javascript"> 
      var map = new GMap2(document.getElementById("map"));
      var point = new GLatLng(51.49, -0.12);
      var marker = new GMarker(point, { draggable: true });

      map.setCenter(point, 8);
      map.addOverlay(marker);

      function toggleDrag() {
        if (marker.draggingEnabled()) {
          marker.disableDragging();
        }
        else {
          marker.enableDragging();
        }
      }
   </script> 
</body> 
</html>
Daniel Vassallo
Brilliant, thanks Daniel.
Sivakanesh