Reputation: 51
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
Inside the onEachFeature function, what I'm trying to achieve is, to update the draggable options on an element click, something like:
$(document).on('click','#someButton',function(){
layer.options.draggable = True; //Only one specific marker
});
This way I would like to have all my marker with draggable options disabled, then on a button click, enable the draggable option, only for one specific marker. Is it possible to achieve this using geojson layer? I also have this geojson layer inside a featureGroup, hope you guys can help me out. Thanks
Upvotes: 0
Views: 2328
Reputation: 19059
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
)
Upvotes: 1
Reputation: 53185
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);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js"></script>
<div id="map" style="height: 150px"></div>
<button id="dragonoff">Enable / Disable dragging</button>
Whether you create your Marker through a GeoJSON Leaflet layer group or not is irrelevant.
Upvotes: 0