leaflet绘制多边形
时间: 2023-12-07 13:05:14 浏览: 184
Leaflet是一个非常流行的JavaScript库,它可以用来创建交互式的Web地图。要绘制多边形,需要使用Leaflet的绘图插件——Leaflet.draw。
下面是一个简单的示例:
1. 引入Leaflet和Leaflet.draw库
```html
<!-- Leaflet -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.js"></script>
<!-- Leaflet.draw -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"></script>
```
2. 创建地图容器
```html
<div id="map" style="width: 100%; height: 400px;"></div>
```
```javascript
// 初始化地图
var map = L.map('map').setView([51.505, -0.09], 13);
// 添加OSM地图图层
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
maxZoom: 18
}).addTo(map);
```
3. 添加绘图工具
```javascript
// 添加绘图工具
var drawControl = new L.Control.Draw({
draw: {
polygon: true, // 允许绘制多边形
polyline: false,
rectangle: false,
circle: false,
marker: false,
circlemarker: false
},
edit: {
featureGroup: drawnItems // 将绘制的图形添加到drawnItems图层
}
}).addTo(map);
```
4. 处理绘制完成事件
```javascript
// 处理绘制完成事件
map.on('draw:created', function(e) {
var layer = e.layer;
drawnItems.addLayer(layer);
});
```
完整代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Draw Demo</title>
<!-- Leaflet -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.js"></script>
<!-- Leaflet.draw -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 400px;"></div>
<script>
// 初始化地图
var map = L.map('map').setView([51.505, -0.09], 13);
// 添加OSM地图图层
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
maxZoom: 18
}).addTo(map);
// 添加绘图工具
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw: {
polygon: true, // 允许绘制多边形
polyline: false,
rectangle: false,
circle: false,
marker: false,
circlemarker: false
},
edit: {
featureGroup: drawnItems // 将绘制的图形添加到drawnItems图层
}
}).addTo(map);
// 处理绘制完成事件
map.on('draw:created', function(e) {
var layer = e.layer;
drawnItems.addLayer(layer);
});
</script>
</body>
</html>
```
运行代码,你可以在地图上用鼠标绘制多边形。绘制完成后,多边形将会被添加到地图上。
阅读全文