使用 leaflet.FreeDraw 和 leaflet.path.drag

Using leaflet.FreeDraw with leaflet.path.drag

我想知道是否可以使用 Leaflet.FreeDraw with leaflet.path.drag 来拖动由 FreeDraw 插件创建的多边形。

jsfiddle

我试过像这样启用拖动插件,但是没有用。

const map = new L.Map(document.querySelector('section.map'), { doubleClickZoom: false }).setView(LAT_LNG, 14);
L.tileLayer(TILE_URL).addTo(map);
const freeDraw = new FreeDraw({ mode: FreeDraw.ALL });
map.addLayer(freeDraw);

freeDraw.dragging.enable();

您可以通过侦听 markers 事件从 FreeDraw 中提取边界,以使用 dragging 启用的传单创建 polygon 或其他地图对象。请参阅下面的工作示例。

您应该考虑是否要使用选项 leaveModeAfterCreate:true 禁用 FreeDraw after this,因为用户在拖动时可能会得到额外的多边形

const LAT_LNG = [51.505, -0.09];
const TILE_URL = 'https://cartodb-basemaps-a.global.ssl.fastly.net/light_all/{z}/{x}/{y}@2x.png';

const map = new L.Map(document.querySelector('section.map'), { doubleClickZoom: false }).setView(LAT_LNG, 14);
L.tileLayer(TILE_URL).addTo(map);
const freeDraw = new FreeDraw({ 
mode: FreeDraw.ALL,
leaveModeAfterCreate:true //recommended to prevent undesired creation of multiple polygons
});
map.addLayer(freeDraw);

//freeDraw.dragging.enable();

//STEP 1: Listen to markers event raised by free draw whenever edits (create/edit/deletions are made to the map)
freeDraw.on("markers",function(event){
  //we are only interested in create events
  //we aim to extract the bounds and remove the existing
  //  freedraw references. If it is that you would like your
  //  user to edit the polygon, then you may keep these and do the   //  additional work to manage and update these references
  if(event.eventType=='create' && event.latLngs.length > 0){ 
  
     //capture the current polygon bounds (store in 1st position)
     var latLngs = event.latLngs[0];
     freeDraw.clear(); //clear freedraw markers
     //create polygon from lat lng bounds retrieved
     var polygon = L.polygon(
         latLngs.map(function(latLng){
             return [latLng.lat,latLng.lng];
         }), {
            color: 'red',
            draggable: true //make polygon draggable
         }).addTo(map);
     
  
  }
})
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.map {
  width: 100vw;
  height: 100vh;
}

.map.mode-create {
    cursor: crosshair;
}

.leaflet-edge {
    background-color: #95bc59;
    box-shadow: 0 0 0 2px white, 0 0 10px rgba(0, 0, 0, .35);
    border-radius: 50%;
    cursor: move;
    outline: none;
    transition: background-color .25s;
}

.leaflet-polygon {
    fill: #b4cd8a;
    stroke: #50622b;
    stroke-width: 2;
    fill-opacity: .75;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.2/leaflet.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.2/leaflet-src.js"></script>


<script src="https://rawgit.com/Wildhoney/Leaflet.FreeDraw/master/dist/leaflet-freedraw.iife.js"></script>
<script src="https://npmcdn.com/leaflet.path.drag/src/Path.Drag.js"></script>
<section class="map"></section>

注意。另请参阅 js-fiddle 此处的工作示例 https://jsfiddle.net/ytevLbgs/