Skip to content Skip to sidebar Skip to footer

Leaflet Geojson Update Draggable State Or Marker

I would like to know if it's possible to update the draggable event of a marker inside a GEOJSON layer in leaflet, I know I can do this by adding: layer.options.draggable = True I

Solution 1:

Every L.Marker has a dragging property, which is the marker's Handler for dragging - and Leaflet handlers can be enable()d and disable()d.

The Leaflet documentation about L.Marker's dragging property also explicitly states:

Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see Handler methods). Example:

marker.dragging.disable();

In your specific case, this would mean something like:

$(document).on('click','#someButton',function(){
    layer.dragging.enable();
});

Be aware that this only works for L.Markers - if you are using GeoJSON, do not expect this to work on lines or polygons, or on points that you specifically decided to display as L.Circles or L.CircleMarkers (via the pointToLayer option of L.GeoJSON)

Solution 2:

You can dynamically enable / disable the draggability of a Leaflet Marker by simply removing it from the map, setting (resetting) its draggable option, then re-adding it to the map:

var map = L.map('map').setView([48.86, 2.35], 11);

var marker = L.marker([48.86, 2.35]).addTo(map);

document.getElementById('dragonoff').addEventListener('click', function(event) {
  event.preventDefault();

  // Toggle Marker draggability.
  marker.remove();
  marker.options.draggable = !marker.options.draggable;
  marker.addTo(map);

  alert(marker.options.draggable ? 'Marker is now draggable' : 'Marker is no longer draggable');
});

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
<linkhref="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css"><scriptsrc="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script><divid="map"style="height: 150px"></div><buttonid="dragonoff">Enable / Disable dragging</button>

Whether you create your Marker through a GeoJSON Leaflet layer group or not is irrelevant.

Post a Comment for "Leaflet Geojson Update Draggable State Or Marker"