繪製線段並顯示端點座標

點擊地圖任意處以繪製線段。端點座標顯示方式為 [lng, lat] (x, y)。

範例展示

原始碼

<!DOCTYPE html>
<html>
<head>
    <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="coordindate"></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]
            localIdeographFontFamily: "'Microsoft YaHei', 'Microsoft JhengHei', 'MS Gothic', sans-serif", // 使用客戶端本機字體生成地圖文字,可加快載入速度
            speedLoad: false,
            attributionControl: false
        }).addControl(new gomp.AttributionControl({
            compact: false
        }));

        var coordinateContainer = document.getElementById('coordindate');

        // 定義 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': '#d94600',
                    'line-width': 5
                },
                filter: ['in', '$type', 'LineString']
            });

            // 設定地圖樣式
            map.addLayer({
                id: 'measure-points',
                type: 'circle',
                source: 'geojson',
                paint: {
                    'circle-radius': 5,
                    'circle-color': '#842b00'
                },
                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();
                }

                if (geojson.features.length == 1) {
                    coordinateContainer.style.display = 'none';
                }

                // 在地圖上移除被點擊的點,並重新繪製線段
                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
                        ],
                        "position":[
                            e.point.x,
                            e.point.y
                        ]
                        },
                        "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);
                }
            
                map.getSource('geojson').setData(geojson);
                
                // 顯示各點座標
                coordinateContainer.innerHTML = '';
                if (geojson.features.length > 0) {
                    coordinateContainer.style.display = 'block';
                    geojson.features.forEach(function(feature) {
                        if (feature.geometry.type == "Point") {
                            coordinateContainer.innerHTML += '[' + feature.geometry.coordinates.join(', ') + '] (' + feature.geometry.position.join(', ') + ')<br />';
                        }
                    });
                } else {
                    coordinateContainer.style.display = 'none';
                }
            });
        });
    </script>
</body>
</html>