[Mapbox GL]测量距离

        点击地图上的点来创建线条,使用turf.lineDistance测量距离


<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.css' rel='stylesheet' />
    <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://api.mapbox.com/mapbox.js/plugins/turf/v2.0.2/turf.min.js'></script>
<script>
mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center: [2.3399, 48.8555],
    zoom: 12
});

var distanceContainer = document.getElementById('distance');

// GeoJSON object to hold our measurement features
var geojson = {
    "type": "FeatureCollection",
    "features": []
};

// Used to draw a line between points
var linestring = {
    "type": "Feature",
    "geometry": {
        "type": "LineString",
        "coordinates": []
    }
};

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半径,单位像素 */
            'circle-color': '#000' /* circle颜色 */
        },
        filter: ['in', '$type', 'Point']  /* 依据数据中type过滤 */
    });
    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) {
        var features = map.queryRenderedFeatures(e.point, { layers: ['measure-points'] }); /* 返回满足查询条件参数的可视化GeoJSON特性对象数组 */

        // Remove the linestring from the group
        // So we can redraw it based on the points collection
        if (geojson.features.length > 1) geojson.features.pop();

        // Clear the Distance container to populate it with a new value
        distanceContainer.innerHTML = '';  /* 清空html文本内容 */

        // If a feature was clicked, remove it from the map
        if (features.length) {
            var id = features[0].properties.id;
            geojson.features = geojson.features.filter(function(point) {  /* array.filter(callback):根据callback过滤元素组成新的数组 */
                return point.properties.id !== id;
            });
        } else {
            var point = {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        e.lngLat.lng,
                        e.lngLat.lat
                    ]
                },
                "properties": {
                    "id": String(new Date().getTime())
                }
            };

            geojson.features.push(point);  /* 新增元素 */
        }

        if (geojson.features.length > 1) {
            linestring.geometry.coordinates = geojson.features.map(function(point) {  /* array.map(callback) :根据callback对数组元素进行变换*/
                return point.geometry.coordinates;
            });

            geojson.features.push(linestring); /* 新增数组元素 */

            // Populate the distanceContainer with total distance
            var value = document.createElement('pre');  /* pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。 */
            value.textContent = 'Total distance: ' + turf.lineDistance(linestring).toLocaleString() + 'km'; /* .textContent设置文本内容,toLocaleString():把数组转换为本地字符串。turf.lineDistance(geojson):这里猜测应该是turf.js库的函数 */
            distanceContainer.appendChild(value); /*appendChild() 向元素内的最后添加子元素 */
        }

        map.getSource('geojson').setData(geojson); /* getSource(id):获取对应的source,setData(data):设置source上的data数据 */
    });
});

map.on('mousemove', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['measure-points'] });
    // UI indicator for clicking/hovering a point on the map
    map.getCanvas().style.cursor = (features.length) ? 'pointer' : 'crosshair';  /* 设置光标格式 */
});
</script>

</body>
</html>
原文: https://www.mapbox.com/mapbox-gl-js/example/measure/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值