距離量測

點擊地圖任意處以繪製計算端點距離總和

範例展示

原始碼

copy
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>距離量測 - Map8 Platform Documentation</title>
    <link rel="stylesheet" href="https://api.map8.zone/css/gomp.css?key=[YOUR_KEY_HERE]" />
    <style>
        #map{
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <div id="distance"></div>

    <script type="text/javascript" src="https://api.map8.zone/maps/js/gomp.js?key=[YOUR_KEY_HERE]"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.min.js"></script>
    <script type="text/javascript">
        gomp.accessToken = '[YOUR_KEY_HERE]';
        var map = new gomp.Map({
            container: 'map', // 地圖容器 ID
            style: 'https://api.map8.zone/styles/go-life-maps-tw-style-std/style.json', // 地圖樣式檔案位置
            maxBounds: [[105, 15], [138.45858, 33.4]], // 台灣地圖區域
            center: [121.54885, 25.037853], // 初始中心座標,格式為 [lng, lat]
            zoom: 16, // 初始 ZOOM LEVEL; [0-20, 0 為最小 (遠), 20 ;最大 (近)]
            minZoom: 6, // 限制地圖可縮放之最小等級, 可省略, [0-19.99]
            maxZoom: 19.99, // 限制地圖可縮放之最大等級, 可省略 [0-19.99]
            speedLoad: false,
            attributionControl: false
        }).addControl(new gomp.AttributionControl({
            compact: false
        }));

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

        // 定義 GeoJSON 物件
        var geojson = {
            "type": "FeatureCollection",
            "features": []
        };
        
        // 線段設定
        var linestring = {
            "type": "Feature",
            "geometry": {
                "type": "LineString",
                "coordinates": []
            }
        };
        map.on('load', function () {
            map.addSource('geojson', {
                "type": "geojson",
                "data": geojson
            });
    
            map.addLayer({
                id: 'measure-lines',
                type: 'line',
                source: 'geojson',
                layout: {
                    'line-cap': 'round',
                    'line-join': 'round'
                },
                paint: {
                    'line-color': '#91a7ff',
                    'line-width': 5
                },
                filter: ['in', '$type', 'LineString']
            });

            map.addLayer({
                id: 'measure-points',
                type: 'circle',
                source: 'geojson',
                paint: {
                    'circle-radius': 5,
                    'circle-color': '#3b5bdb'
                },
                filter: ['in', '$type', 'Point']
            });
    
            map.on('click', function(e) {
                var features = map.queryRenderedFeatures(e.point, { layers: ['measure-points'] });
            
                if (geojson.features.length > 1) geojson.features.pop();
                
                // 清除距離文字
                distanceContainer.innerHTML = '';
            
                // 在地圖上移除被點擊的點,並重新繪製線段
                if (features.length) {
                    var id = features[0].properties.id;
                    geojson.features = geojson.features.filter(function(point) {
                        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) {
                        return point.geometry.coordinates;
                    });
                    
                    geojson.features.push(linestring);
                    
                    // 顯示總距離
                    distanceContainer.style.display = 'block';
                    distanceContainer.textContent = '距離:' + turf.lineDistance(linestring).toLocaleString() + 'km';
                } else {
                    distanceContainer.style.display = 'none';
                }
                
                map.getSource('geojson').setData(geojson);
            });
        });
    </script>
</body>
</html>