h3c*_*t0r 6 javascript leaflet
有没有办法使用Leaflet绘图插件以编程方式添加多边形?https://github.com/Leaflet/Leaflet.draw
例如:单击一个按钮并添加一个可由插件编辑的正方形.
谢谢!
您只需将多边形(或您想要编辑的任何其他图层)添加到传递给控件edit.featureGroup选项的功能组中L.Control.Draw.
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.
});
Run Code Online (Sandbox Code Playgroud)
稍后可以通过单击"编辑图层"按钮(如果启用该功能)来编辑该功能组中的所有内容.
现场演示:
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()
];
}Run Code Online (Sandbox Code Playgroud)
html,
body,
#map {
height: 100%;
margin: 0;
}
#button {
z-index: 1050;
position: absolute;
top: 10px;
left: 50px;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)