<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Highlight features within a bounding box</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css" rel="stylesheet" />
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<style>
.boxdraw {
background: yellow;
border: 2px solid #3887be;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
</style>
<div id="map"></div>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
mapboxgl.accessToken = 'pk.eyJ1IjoiaGRuYXYiLCJhIjoiY2thMmczaGNkMGNhZTNnbWUxbnR3eWt3dSJ9.UZBPD5GXeHi0BAbuDEv4pA';
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();
console.log('canvas',canvas);
// 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.
//按shift加鼠标选中后的图层
map.addLayer(
{
'id': 'counties-highlighted',
'type': 'fill',
'source': 'counties',
'source-layer': 'original',
'paint': {
'fill-outline-color': '#484896',
'fill-color': '#000',
'fill-opacity': 0.75
},
'filter': ['in', 'FIPS', '']
},
'settlement-label'
); // Place polygon under these labels.
// 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) {
var rect = canvas.getBoundingClientRect();
console.log("rect",rect);
console.log('e.clientX',e.clientX);
console.log('rect.left',rect.left);
console.log('canvas.clientLeft',canvas.clientLeft);
return new mapboxgl.Point(
e.clientX - rect.left - canvas.clientLeft,
e.clientY - rect.top - canvas.clientTop
);
}
function mouseDown(e) {
console.log('触发事件');
// Continue the rest of the function if the shiftkey is pressed.
if (!(e.shiftKey && 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);
document.addEventListener('keydown', onKeyDown);
// Capture the first xy coordinates
start = mousePos(e);
console.log('start',start);
}
function onMouseMove(e) {
// Capture the ongoing xy coordinates
current = mousePos(e);
// Append the box element if it doesnt exist
if (!box) {//box为shift加鼠标形成的选择框的颜色
box = document.createElement('div');
box.classList.add('boxdraw');
canvas.appendChild(box);
console.log('box',box);
}
var minX = Math.min(start.x, current.x),
maxX = Math.max(start.x, current.x),
minY = Math.min(start.y, current.y),
maxY = Math.max(start.y, current.y);
// Adjust width and xy position of the box element ongoing
var pos = 'translate(' + minX + 'px,' + minY + 'px)';
box.style.transform = pos;
box.style.WebkitTransform = pos;
box.style.width = maxX - minX + 'px';
box.style.height = maxY - minY + 'px';
}
function onMouseUp(e) {
// Capture xy coordinates
finish([start, mousePos(e)]);
}
function onKeyDown(e) {
// If the ESC key is pressed
if (e.keyCode === 27) finish();
}
function finish(bbox) {
// Remove these events now that finish has been called.
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('keydown', onKeyDown);
document.removeEventListener('mouseup', onMouseUp);
if (box) {
box.parentNode.removeChild(box);
box = null;
}
// If bbox exists. use this value as the argument for `queryRenderedFeatures`
if (bbox) {
var features = map.queryRenderedFeatures(bbox, {
layers: ['counties']
});
console.log('要素数组',features);
if (features.length >= 1000) {
return window.alert('Select a smaller number of features');
}
// 运行选定的功能并设置过滤器
// 将功能与要激活的唯一FIPS代码匹配
// the `counties-highlighted` layer.
var filter = features.reduce(
function(memo, feature) {
console.log('memo',memo);
memo.push(feature.properties.FIPS);
return memo;
},
['in', 'FIPS']
);
console.log('filter',filter);
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>
其中:
1.var canvas = map.getCanvasContainer();
该代码是获取地图dom结构对象,可以在上面加一些按键及鼠标监听
2.var rect = canvas.getBoundingClientRect();
该代码是获取一个dom结构在距离浏览器窗口上和左的距离,如下图所示:详情请见如下链接
https://www.webhek.com/post/getclientrects-getboundingclientrect.html
3.var filter = features.reduce(
function(memo, feature) {
console.log('memo',memo);
memo.push(feature.properties.FIPS);
return memo;
},
['in', 'FIPS']
);
组成layer图层过滤器,reduce函数是一个累加器,回调函数中的memo其实就是reduce函数的第二个参数['in', 'FIPS'],
执行结果就是从数组features中提取FIPS属性值,push到['in', 'FIPS']中并返回结果给var filter
然后map.setFilter('counties-highlighted', filter);添加图层过滤器