Leaflet Geojson Update Draggable State Or Marker
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.Marker
s - 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.Circle
s or L.CircleMarker
s (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: '© <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"