首先,上效果图:
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;//50像素长度在该线段上的等分因子factor
var dradio = 1;//投影坐标系3857下设置1,在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);