Leaflet geojson 更新可拖动状态或标记

Leaflet geojson update draggable state or marker

我想知道是否可以更新传单中 GEOJSON 层内标记的可拖动事件,我知道我可以通过添加来做到这一点:

layer.options.draggable = True

在 onEachFeature 函数中,我想要实现的是更新元素点击时的可拖动选项,例如:

$(document).on('click','#someButton',function(){
    layer.options.draggable = True; //Only one specific marker
});

通过这种方式,我希望禁用所有带有可拖动选项的标记,然后单击按钮,启用可拖动选项,仅针对一个特定标记。是否可以使用 geojson 层实现此目的?我在 featureGroup 中也有这个 geojson 层,希望你们能帮帮我。谢谢

您可以动态启用/禁用传单标记的可拖动性,只需将其从地图中删除,设置(重置)其 draggable 选项,然后将其重新添加到地图:

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);
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>

<div id="map" style="height: 150px"></div>

<button id="dragonoff">Enable / Disable dragging</button>

您是否通过 GeoJSON Leaflet 图层组创建标记是无关紧要的。

每个 L.Marker 都有一个 dragging 属性,这是用于拖动的标记 Handler - Leaflet 处理程序可以是 enable()d 和 disable()d.

Leaflet documentation about L.Marker's dragging property 也明确指出:

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();

在您的特定情况下,这意味着:

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

请注意,这仅适用于 L.Markers - 如果您使用的是 GeoJSON,请不要指望它适用于直线或多边形,或者您明确决定显示为 [=21= 的点]s 或 L.CircleMarkers(通过 L.GeoJSONpointToLayer 选项)