Is there a way to add a polygon programmatically using the Leaflet draw plugin? https://github.com/Leaflet/Leaflet.draw
For example: click a button and add a square that can be edited by the plugin.
You just need to add your polygon (or whatever other layer that you want to be editable) to the Feature Group that you pass to the edit.featureGroup
option of your L.Control.Draw
control.
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.
});
Everything that is in that Feature Group can later be edited by clicking on the "Edit layers" button (if that functionality is enabled).
Live demo:
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: '© <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/[email protected]/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js" integrity="sha512-+ZaXMZ7sjFMiCigvm8WjllFy6g3aou3+GZngAtugLzrmPFKFK7yjSri0XnElvCTu/PrifAYQuxZTybAEkA8VOA==" crossorigin=""></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.draw.
css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.draw-src.js"></script>
<div id="map"></div>
<button id="button">Add editable rectangle</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With