mapbox gl 测量

一、代码





Measure distances








二、截图

三、知识点 

1、相同数据源添加点、线

// 点
filter: ['in', '$type', 'Point']

// 线
filter: ['in', '$type', 'LineString']

2、地图点击事件获取指定图层要素

map.on('click', (e) => {
      const features = map.queryRenderedFeatures(e.point, {
            layers: ['measure-points']
      });
})

3、修改地图鼠标手势

 map.getCanvas().style.cursor = features.length
            ? 'pointer'
            : 'crosshair';

 4、添加点、线图层

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'
            },
            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']
        });

5、turf 计算长度

let linestring = {
        'type': 'Feature',
        'geometry': {
            'type': 'LineString',
            'coordinates': []
        }
    };

const geojson = {
        'type': 'FeatureCollection',
        'features': []
    };

 linestring.geometry.coordinates = geojson.features.map(
                    (point) => point.geometry.coordinates
                );

const distance = turf.length(linestring);

你可能感兴趣的:(前端,linux,javascript)