mapbox 实现框查圈查资源图层 具体实现代码
时间: 2024-02-25 12:57:44 浏览: 140
以下是一个简单的示例,演示如何在Mapbox上实现框查圈查资源图层。这个示例使用的是Mapbox的JavaScript API和Turf.js库来处理地理数据。
```javascript
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Mapbox框查圈查资源图层示例</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox-gl-js/v2.4.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.4.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://api.mapbox.com/mapbox.js/plugins/turf/v3.0.11/turf.min.js'></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.mapboxgl-popup { max-width: 400px; }
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = '<your access token>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-73.986, 40.743],
zoom: 13
});
// 添加一个标记层
map.on('load', function() {
map.addSource('markers', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-73.986, 40.743]
},
properties: {
name: '地点1'
}
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-73.984, 40.741]
},
properties: {
name: '地点2'
}
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [-73.985, 40.744]
},
properties: {
name: '地点3'
}
}
]
}
});
map.addLayer({
id: 'markers',
source: 'markers',
type: 'circle',
paint: {
'circle-radius': 8,
'circle-color': '#007cbf'
}
});
});
// 添加一个框查圈查控件
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
rectangle: true,
circle: true,
point: false,
line_string: false,
polygon: false,
trash: true
}
});
map.addControl(draw);
// 框查圈查时触发
map.on('draw.selectionchange', function(e) {
var features = map.queryRenderedFeatures(e.features[0]);
// 计算被选中的要素的中心点
var centroid = turf.centroid(turf.featureCollection(features));
// 显示选中要素的信息
var popup = new mapboxgl.Popup()
.setLngLat(centroid.geometry.coordinates)
.setHTML('<h3>' + features.length + '个要素被选中</h3><p>' + features.map(function(feature) {
return feature.properties.name;
}).join(', ') + '</p>')
.addTo(map);
});
</script>
</body>
</html>
```
这个示例添加了一个标记层,并给地图添加了一个框查圈查控件。当用户在地图上框选或圈选时,代码会查询被选中的要素,并计算它们的中心点。然后,代码会显示一个弹出窗口,其中包含被选中要素的信息。
阅读全文