Search code examples
google-mapsgoogle-maps-api-3google-maps-markers

Enabling and disabling dragging markers by checkbox


I am working on this demo. How can I make the markers draggable when the check box is unchecked? All markers have their own associated checkbox, which means that user can lock each marker which they want (not all together).

Initially all markers are unchecked when they loaded to page. And finally I need to change the icon when the marker checked as lock.

  var contentString = ' -- Lock <input name="your_name" value="your_value" type="checkbox">';
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  var infowindow =  new google.maps.InfoWindow({ content: "" });
  var data = {
        "markers": [{
                "latitude": 11.606503,
                "longitude": 122.712637,
                "title": "Copenhagen"
            }, {
                "latitude": 11.585988,
                "longitude": 122.757084,
                "title": "Barcelona"
            }
        ]
    };
    locations.length = 0;
    for (p = 0; p < data.markers.length; p++) {
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(data.markers[p].latitude, data.markers[p].longitude),
            map: map,
            draggable: true,
            title: "marker " + p,
            id: p
        });

        bindMarker(marker);
        bindInfoWindow(marker, map, infowindow, data.markers[p].title);
    }

    function bindMarker(marker) {
        google.maps.event.addListener(marker, 'dragend', function () {
   marker.setIcon('https://www.google.com/mapfiles/marker_green.png');
        });
        google.maps.event.addListener(marker, 'click', function () {
        });
    }
    function bindInfoWindow(marker, map, infowindow, strDescription) {
google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(strDescription + contentString);
    infowindow.open(map, marker);
});
}
});

Update

Code:

  function bindMarkerDrag(marker){
        google.maps.event.addListener(checkbox, "click", function(){
            draggable: false
         //marker.setClickable(checkbox.checked);
      });
        }

then I add the following inside the loop:

 bindMarkerDrag(marker);

Here is a demo, but it is not working.


Solution

  • As I said in my comment, you need to add checkbox.checked = !marker.getDraggable(); in your marker click event listener. Not in the checkbox event listener.

    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.checked = !marker.getDraggable();
    checkbox.addEventListener('click', function () {
        marker.setDraggable(!this.checked);
    });
    
    1. Create the checbox
    2. Check it or not if the marker is draggable or not
    3. Manage the checkbox click event