我正在寻找stackoverflow上的这个问题的解决方案,但由于我找不到准确的解决方案,我最终自己解决它并在此发布,希望它有所帮助。
Google地图为您提供折线功能,该功能基于坐标列表可以绘制一系列连接所有线条的线条。
您可以使用以下代码使用单个箭头绘制折线:
var allCoordinates = [
new google.maps.LatLng(26.291, 148.027),
new google.maps.LatLng(26.291, 150.027),
new google.maps.LatLng(22.291, 153.027),
new google.maps.LatLng(18.291, 153.027)
];
var polyline = new google.maps.Polyline({
path: allCoordinates,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
geodesic: true,
icons: [{
icon: {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW},
offset: '100%'
}]
});
这里的问题是箭头将仅在最后一段中绘制,如下图所示,但有时路线可能不那么简单,我们需要在每个段上添加一个箭头。
图标定义中的“重复”属性可能是另一种选择,但只允许以像素为单位定义度量,并且definelty与折线上的每个方向变化都不匹配。
因此,我发现实现这一目标的一种方法是制作多条折线,每个区段允许一条折线,在这种情况下允许在每条折线上绘制箭头。这是代码:
var allCoordinates = [
new google.maps.LatLng(26.291, 148.027),
new google.maps.LatLng(26.291, 150.027),
new google.maps.LatLng(22.291, 153.027),
new google.maps.LatLng(18.291, 153.027)
];
for (var i = 0, n = allCoordinates.length; i < n; i++) {
var coordinates = new Array();
for (var j = i; j < i+2 && j < n; j++) {
coordinates[j-i] = allCoordinates[j];
}
var polyline = new google.maps.Polyline({
path: coordinates,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
geodesic: true,
icons: [{
icon: {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW},
offset: '100%'
}]
});
polyline.setMap(map);
polylines.push(polyline);
}
这是图片:
我希望这对任何想要这样的人都有用!
图标选项对象有一个重复属性。 example of dashed lines from the Google Maps JS API显示了一种方法,可以在线上重复符号而不是创建新的折线。在您的示例的上下文中,它看起来像这样:
var allCoordinates = [
new google.maps.LatLng(26.291, 148.027),
new google.maps.LatLng(26.291, 150.027),
new google.maps.LatLng(22.291, 153.027),
new google.maps.LatLng(18.291, 153.027)
];
var polyline = new google.maps.Polyline({
path: allCoordinates,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
geodesic: true,
icons: [{
icon: {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW},
offset: '100%',
repeat: '20px'
}]
});
polyline.setMap(map);
polylines.push(polyline);
这会沿着线创建箭头,如下所示:
这是一个带有更简单循环和自定义符号的版本,因此您可以根据需要调整大小和修改它 - google.maps.SymbolPath.FORWARD_CLOSED_ARROW
是固定大小 - scale
属性不会影响它。
const drawLines = (map, maps, places) => {
const arrow = {
path: 'M 0,0 5,15 -5,15 0,0 z', // 0,0 is the tip of the arrow
fillColor: 'red',
fillOpacity: 1.0,
strokeColor: 'red',
strokeWeight: 1,
};
const newLines = [];
for (let i = 0; i < places.length - 1; i++) {
const line = new maps.Polyline({
path: places.slice(i, i+2),
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
icons: [{
icon: arrow,
offset: '100%',
}]
});
line.setMap(map);
newLines.push(line);
}
}