首先,上效果圖:
Openlayers繪制帶箭頭的路線只用到了ol.FeatureStyleFunction,簡單易懂,詳細步驟及代碼如下:
第一步,創建線要素:
var line_feature = new ol.Feature();
var line_geom=new ol.geom.LineString(paths);
line_feature.setGeometry(line_geom)
第二步,創建線圖層並添加到地圖對象中
var polyLineLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [ine_feature]
}),
});
map.addLayer(polyLineLayer);
第三步,設置styleFunction,ol.FeatureStyleFunction只有一個參數resolution,詳細代碼如下:
var styles=function (resolution) {
var geometry = this.getGeometry();
var length = geometry.getLength();//獲取線段長度
var radio = (50 * resolution) / length;
var dradio = 1;//投影坐標系,如3857等,在EPSG:4326下可以設置dradio=10000
var styles = [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "green",
width: 10,
})
})
];
for (var i = 0; i <= 1; i += radio) {
var arrowLocation = geometry.getCoordinateAt(i);
geometry.forEachSegment(function (start, end) {
if (start[0] == end[0] || start[1] == end[1]) return;
var dx1 = end[0] - arrowLocation[0];
var dy1 = end[1] - arrowLocation[1];
var dx2 = arrowLocation[0] - start[0];
var dy2 = arrowLocation[1] - start[1];
if (dx1 != dx2 && dy1 != dy2) {
if (Math.abs(dradio * dx1 * dy2 - dradio * dx2 * dy1) < 0.001) {
var dx = end[0] - start[0];
var dy = end[1] - start[1];
var rotation = Math.atan2(dy, dx);
styles.push(new ol.style.Style({
geometry: new ol.geom.Point(arrowLocation),
image: new ol.style.Icon({
src: 'assets/imgs/routearrow.png',
anchor: [0.75, 0.5],
rotateWithView: false,
rotation: -rotation + Math.PI
})
}));
}
}
});
}
return styles;
}
最后,給feature要素設置樣式即可
line_feature.setStyle(styles);
ps:如該文章對你有幫助,歡迎評論,謝謝!