<!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="https://api.mapbox.com/mapbox-gl-js/v2.3.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/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="https://unpkg.com/@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 = document.getElementById('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': {
'type': 'LineString',
'coordinates': []
}
};
// map load完之后,addSource和addLayer
map.on('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']
});
// 点击触发事件函数
map.on('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个元素的时候,开始添加linestring.geometry.coordinates
if (geojson.features.length > 1) {
// map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
linestring.geometry.coordinates = geojson.features.map(
function (point) {
return point.geometry.coordinates;
}
);
// 把linestring 添加到 features array 的最后
// 再次点击的时候,就把它pop()弹出
geojson.features.push(linestring);
// Populate the distanceContainer with total distance
var value = document.createElement('pre');
value.textContent =
'Total distance: ' +
// turf.length(linestring) 传入一个geojson <(LineString|MultiLineString)>
// turf.length(linestring) 返回 number - length of GeoJSON
// number.toLocaleString() 返回 Number 对象转换为本地格式的字符串。这里是保留小数点后三位
// date.toLocaleString() 可根据本地时间把 Date 对象转换为字符串,并返回结果。
turf.length(linestring).toLocaleString() +
'km';
distanceContainer.appendChild(value);
}
// 每次点击都更新 geojson 数据源的数据
map.getSource('geojson').setData(geojson);
});
});
map.on('mousemove', function (e) {
//
var features = map.queryRenderedFeatures(e.point, {
layers: ['measure-points']
});
// UI indicator for clicking/hovering a point on the map
// 改变鼠标的形状 pointer 或者 crosshair
map.getCanvas().style.cursor = features.length
? 'pointer'
: 'crosshair';
});
</script>
</body>
</html>