Mapbox-gl实现距离测量源码解读
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Measure distances</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="api.mapbox/mapbox-gl-js/v2.3.0/mapbox-gl.css" rel="stylesheet">
<script src="api.mapbox/mapbox-gl-js/v2.3.0/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<style>
.distance-container {
position: absolute;
top: 10px;
left: 10px;
z-index: 1;
}
.
distance-container > * {
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 11px;
line-height: 18px;
display: block;
margin: 0;
padding: 5px 10px;
border-radius: 3px;
}
</style>
<div id="map"></div>
<div id="distance" class="distance-container"></div>
<script src="unpkg/@turf/turf@6/turf.min.js"></script>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiYWdhbmxpYW5nIiwiYSI6ImNrYndkZ2dqdzBldzQycmxna3RrZ3ZrMDIifQ.mMruQKqeJPDcqpV7HEFSLA';    var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [2.3399, 48.8555],
zoom: 12
});
var distanceContainer = ElementById('distance');
// GeoJSON object to hold our measurement features
// ⽤于保存points和linestring, linestring 元素保存于列表最后
var geojson = {
'type': 'FeatureCollection',
'features': []
};
// Used to draw a line between points
// 保存由points 连接⽽成的linestring
// 它也是⼀个符合标准的geojson
var linestring = {
'type': 'Feature',
'geometry': {
'geometry': {
'type': 'LineString',
'coordinates': []
}
};
// map load完之后,addSource和addLayer
<('load', function () {
map.addSource('geojson', {
'type': 'geojson',
'data': geojson
});
// Add styles to the map
map.addLayer({
id: 'measure-points',
type: 'circle',
source: 'geojson',
paint: {
'circle-radius': 5,
'circle-color': '#000'
},
/
/ 过滤geojson⾥⾯的某⼀些type
filter: ['in', '$type', 'Point']
});
map.addLayer({
id: 'measure-lines',
type: 'line',
source: 'geojson',
layout: {
'line-cap': 'round',
'line-join': 'round'
},
paint: {
'line-color': '#000',
'line-width': 2.5
},
filter: ['in', '$type', 'LineString']
});
// 点击触发事件函数
<('click', function (e) {
// queryRenderedFeatures(geometry?,options?)
// geometry((PointLike | Array<PointLike>)?)
var features = map.queryRenderedFeatures(e.point, {
layers: ['measure-points']
});
// Remove the linestring from the group
// So we can redraw it based on the points collection
// linestring 总是 geojson.features的最后⼀个元素
// pop() 函数删除数组⾥⾯的最后⼀个元素,并返回最后⼀个元素。  // 删除之后,接下来再重新添加和绘制
if (geojson.features.length > 1) geojson.features.pop();
// Clear the Distance container to populate it with a new value    // 清空显⽰框
distanceContainer.innerHTML = '';
// If a feature was clicked, remove it from the map
if (features.length) {
var id = features[0].properties.id;
// filter() ⽅法创建⼀个新的数组,
// 新数组中的元素是通过检查指定数组中符合条件的所有元素。
geojson.features = geojson.features.filter(function (point) {                    return point.properties.id !== id;
});
});
} else {
// 没有点击 point,那么就添加⼀个point
var point = {
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [e.lngLat.lng, e.lngLat.lat]
},
'properties': {
// getTime() ⽅法可返回距1970年1⽉1⽇之间的毫秒数。
'id': String(new Date().getTime())
}
};
// push() ⽅法可向数组的末尾添加⼀个或多个元素,并返回新的长度。
geojson.features.push(point);
}
/
/ 具有多于1个元素的时候,开始添加dinates
if (geojson.features.length > 1) {
// map() ⽅法返回⼀个新数组,数组中的元素为原始数组元素调⽤函数处理后的值。
function (point) {
ry.coordinates;borderbox
}
);
// 把linestring 添加到 features array 的最后
// 再次点击的时候,就把它pop()弹出
geojson.features.push(linestring);
/
/ Populate the distanceContainer with total distance
var value = ateElement('pre');
'Total distance: ' +
// turf.length(linestring) 传⼊⼀个geojson <(LineString|MultiLineString)>
// turf.length(linestring) 返回 number - length of GeoJSON
// LocaleString() 返回  Number 对象转换为本地格式的字符串。这⾥是保留⼩数点后三位    // LocaleString() 可根据本地时间把 Date 对象转换为字符串,并返回结果。
turf.length(linestring).toLocaleString() +
'km';
distanceContainer.appendChild(value);
}
// 每次点击都更新 geojson 数据源的数据
});
});
<('mousemove', function (e) {
//
var features = map.queryRenderedFeatures(e.point, {
layers: ['measure-points']
});
// UI indicator for clicking/hovering a point on the map
// 改变⿏标的形状 pointer 或者 crosshair
'pointer'
: 'crosshair';
});
</script>
</body>
</html>