需求
Mapbox官方示例只实现了点选和框选的空间查询方式,而在实际开发中也需要实现画圆并高亮圆内的要素。
实现思路
- 使用Canvas实现动态画圆
- 根据圆心和鼠标所在位置,计算出半径,在map上创建circle图层
- 通过turf工具函数,查询与圆相交或在圆内的要素
预览效果
与圆相交的要素:
圆内要素:
实现代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Highlight features within a circle</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<link href="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js"></script>
<script src="https://unpkg.com/@turf/turf@6/turf.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.boxdraw {
background: rgba(56, 135, 190, 0.1);
border: 2px solid #3887be;
border-radius: 50%;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = 'your accessToken';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-98, 38.88],
minZoom: 2,
zoom: 3
});
// Disable default box zooming.
map.boxZoom.disable();
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false
});
map.on('load', function () {
var canvas = map.getCanvasContainer();
// Variable to hold the starting xy coordinates
// when `mousedown` occured.
var start;
// Variable to hold the current xy coordinates
// when `mousemove` or `mouseup` occurs.
var current;
// Variable for the draw box element.
var box;
// Add the source to query. In this example we're using
// county polygons uploaded as vector tiles
map.addSource('counties', {
'type': 'vector',
'url': 'mapbox://mapbox.82pkq93d'
});
map.addLayer({
'id': 'counties',
'type': 'fill',
'source': 'counties',
'source-layer': 'original',
'paint': {
'fill-outline-color': 'rgba(0,0,0,0.1)',
'fill-color': 'rgba(0,0,0,0.1)'
}
},
'settlement-label'
); // Place polygon under these labels.
// 高亮图层
map.addLayer({
'id': 'counties-highlighted',
'type': 'fill',
'source': 'counties',
'source-layer': 'original',
'paint': {
'fill-outline-color': '#484896',
'fill-color': '#6e599f',
'fill-opacity': 0.75
},
'filter': ['in', 'FIPS', '']
},
'settlement-label'
); // Place polygon under these labels.
// 圆圈图层
map.addSource('circle', {
'type': 'geojson',
// 空的geojson数据
'data': turf.featureCollection([])
});
map.addLayer({
'id': 'circle',
'type': 'fill',
'source': 'circle',
'paint': {
'fill-outline-color': '#f00',
'fill-color': 'rgba(56, 135, 190, 0.1)',
},
},
'settlement-label'
);
// Set `true` to dispatch the event before other functions
// call it. This is necessary for disabling the default map
// dragging behaviour.
canvas.addEventListener('mousedown', mouseDown, true);
// Return the xy coordinates of the mouse position
function mousePos(e) {
return new mapboxgl.Point(
e.clientX - canvas.clientLeft,
e.clientY - canvas.clientTop
);
}
function mouseDown(e) {
if (e.button !== 0) return;
// Disable default drag zooming when the shift key is held down.
map.dragPan.disable();
// Call functions for the following events
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
// Capture the first xy coordinates
start = mousePos(e);
}
function onMouseMove(e) {
// Capture the ongoing xy coordinates
current = mousePos(e);
// Append the box element if it doesnt exist
if (!box) {
box = document.createElement('div');
box.classList.add('boxdraw');
canvas.appendChild(box);
}
const r = Math.sqrt(Math.pow(Math.abs(current.x - start.x), 2) + Math.pow(Math.abs(current.y - start.y),
2));
const pitch = map.getPitch();
box.style.transform = 'translate(-50%,-50%) rotateX(' + pitch + 'deg)';
box.style.left = start.x + 'px';
box.style.top = start.y + 'px';
box.style.width = r * 2 + 'px';
box.style.height = r * 2 + 'px';
}
function onMouseUp(e) {
// Capture xy coordinates
finish(start, mousePos(e));
}
function finish(from, to) {
// Remove these events now that finish has been called.
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
if (box) {
box.parentNode.removeChild(box);
box = null;
}
// 屏幕坐标转换
const fromCoord = map.unproject([from.x, from.y]),
toCoord = map.unproject([to.x, to.y]);
const fromPoint = turf.point([fromCoord.lng, fromCoord.lat]),
toPoint = turf.point([toCoord.lng, toCoord.lat]);
const distance = turf.distance(fromPoint, toPoint);
// 将数据渲染到圆圈图层
const circle = turf.circle(fromPoint, distance);
map.getSource('circle').setData(turf.featureCollection([circle]));
// If bbox exists. use this value as the argument for `queryRenderedFeatures`
if (circle) {
const bbox = turf.bbox(circle);
// 从source中获取features数据
var features = map.querySourceFeatures('counties', {
sourceLayer: 'original',
});
var intersectFeatures = [];
features.forEach(f => {
// 判断是否相交
if (turf.intersect(f, circle)) {
intersectFeatures.push(f);
}
// if (turf.booleanOverlap(f, circle)) {
// intersectFeatures.push(f);
// }
// 判断是否在圆圈内
// var inCircle = false;
// var explode = turf.explode(f);
// for (let p of explode.features) {
// if (turf.booleanPointInPolygon(p, circle)) {
// inCircle = true;
// } else {
// inCircle = false
// break;
// }
// }
// if (inCircle) {
// intersectFeatures.push(f);
// }
});
// Run through the selected features and set a filter
// to match features with unique FIPS codes to activate
// the `counties-highlighted` layer.
var filter = intersectFeatures.reduce(
function (memo, feature) {
memo.push(feature.properties.FIPS);
return memo;
},
['in', 'FIPS']
);
map.setFilter('counties-highlighted', filter);
}
map.dragPan.enable();
}
map.on('mousemove', function (e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['counties-highlighted']
});
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = features.length ? 'pointer' : '';
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
popup
.setLngLat(e.lngLat)
.setText(feature.properties.COUNTY)
.addTo(map);
});
});
</script>
</body>
</html>