簡體   English   中英

在 Leaflet L.Draw 插件中以編程方式添加多邊形

[英]Add Polygon programmatically in Leaflet L.Draw plugin

有沒有辦法使用 Leaflet draw 插件以編程方式添加多邊形? https://github.com/Leaflet/Leaflet.draw

例如:單擊一個按鈕並添加一個可由插件編輯的方塊。

您只需要將多邊形(或您想要編輯的任何其他圖層)添加到您傳遞給L.Control.Draw控件的edit.featureGroup選項的要素組中。

var editableLayers = L.featureGroup().addTo(map);
var drawControl = new L.Control.Draw({
  edit: {
    featureGroup: editableLayers
  }
});

// Add a new editable rectangle when clicking on the button.
button.addEventListener('click', function (event) {
  event.preventDefault();

  L.rectangle([
    getRandomLatLng(),
    getRandomLatLng()
  ]).addTo(editableLayers); // Add to editableLayers instead of directly to map.
});

以后可以通過單擊“編輯圖層”按鈕(如果啟用該功能)來編輯該要素組中的所有內容。

現場演示:

 var map = L.map('map').setView([48.86, 2.35], 11); var editableLayers = L.featureGroup().addTo(map); var drawControl = new L.Control.Draw({ edit: { featureGroup: editableLayers }, draw: false }).addTo(map); // Add a new editable rectangle when clicking on the button. button.addEventListener('click', function(event) { event.preventDefault(); L.rectangle([ getRandomLatLng(), getRandomLatLng() ]).addTo(editableLayers); // Add to editableLayers instead of directly to map. }); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); function getRandomLatLng() { return [ 48.8 + 0.1 * Math.random(), 2.25 + 0.2 * Math.random() ]; }
 html, body, #map { height: 100%; margin: 0; } #button { z-index: 1050; position: absolute; top: 10px; left: 50px; }
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" /> <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet-src.js" integrity="sha512-+ZaXMZ7sjFMiCigvm8WjllFy6g3aou3+GZngAtugLzrmPFKFK7yjSri0XnElvCTu/PrifAYQuxZTybAEkA8VOA==" crossorigin=""></script> <link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.2/dist/leaflet.draw. css" /> <script src="https://unpkg.com/leaflet-draw@1.0.2/dist/leaflet.draw-src.js"></script> <div id="map"></div> <button id="button">Add editable rectangle</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM