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');
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 控制符號大小,需根據地圖縮放級別調整