萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Google Maps API 繪製虛線路徑的 SVG Symbol 技巧

核心原理

Google Maps Polyline 本身不支援虛線樣式,但可通過 icons 屬性配合 SVG Path 符號實現。關鍵在於定義 lineSymbol 的 path 屬性使用 SVG 路徑語法。

代碼實現

function drawDashedPath(map, coordinates, color = '#2d2d2d') {
    // 定義虛線符號:M=移動到, L=連線到
    // 'M 0,-1 0,1' 表示從(0,-1)畫線到(0,1),形成一個短豎線段
    const lineSymbol = {
        path: 'M 0,-1 0,1',
        strokeOpacity: 1,
        scale: 3,
        strokeColor: color
    };

    const polyline = new google.maps.Polyline({
        path: coordinates,
        strokeColor: color,
        strokeOpacity: 0, // 隱藏實線,僅顯示圖標
        strokeWeight: 2,
        icons: [{
            icon: lineSymbol,
            offset: '0',
            repeat: '20px' // 虛線間距
        }],
        map: map
    });

    return polyline;
}

// 使用示例
const pathCoords = [
    new google.maps.LatLng(37.772323, -122.214897),
    new google.maps.LatLng(21.291982, -157.821856),
    new google.maps.LatLng(-18.142599, 178.431),
    new google.maps.LatLng(-27.46758, 153.027892)
];
drawDashedPath(map, pathCoords, '#ff0000');

SVG Path 語法解析

  • M x,y:移動畫筆到絕對座標
  • L x,y:畫直線到絕對座標
  • m x,y / l x,y:相對座標版本
  • Z:閉合路徑

示例中 'M 0,-1 0,1' 等同於 'M 0,-1 L 0,1',繪製長度為 2 的垂直線段。配合 repeat: '20px' 形成虛線效果。

進階應用:箭頭虛線(表示方向)

const arrowSymbol = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    scale: 3,
    strokeColor: '#fff',
    fillColor: '#2d2d2d',
    fillOpacity: 1
};

icons: [{
    icon: lineSymbol,
    offset: '0',
    repeat: '20px'
}, {
    icon: arrowSymbol,
    offset: '100%', // 終點顯示箭頭
    repeat: '0'
}]

注意事項

  • strokeOpacity: 0 隱藏底層實線,僅通過 icons 顯示
  • scale 控制符號大小,需根據地圖縮放級別調整
  • 大量路徑渲染時注意性能,可簡化座標點
copyright © 萬盛學電腦網 all rights reserved