本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。
源码 见 1053.html ,对应的 官网示例
https://openlayers.org/en/latest/examples/line-arrows.html?q=draw
https://openlayers.org/en/latest/examples/draw-features.html?q=Drag
image.png image.png 打开自由绘制开关后的效果 freehand = trueStyleFunction
ol.geom.LineString.forEachSegment
API说明没有用法,怎样查?
<!DOCTYPE html>
<html>
<head>
<title>绘制带箭头的直线</title>
<link rel="stylesheet" href="../include/ol.css" type="text/css" />
<script src="../include/ol.js"></script>
</head>
<style></style>
<body>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector();
//获取样式化的要素的几何,定义样式数组,遍历
var styleFunction = function (feature) {
var geometry = feature.getGeometry();
var styles = [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ffcc77',
width: 2
})
})
];
//遍历每一个线段,对每一个线段做一个回调函数,
geometry.forEachSegment(function (start, end) {
var dx = end[0] - start[0];
var dy = end[1] - start[1];
var rotation = Math.atan2(dy, dx);//计算直线的前进方向(选中角度)
styles.push(new ol.style.Style({ //最后一个点,增加一个样式png,调整这个样式的旋转角度
geometry: new ol.geom.Point(end),
image: new ol.style.Icon({
src: '../data/arrow.png',
anchor: [0.75, 0.5],
rotateWithView: true,
rotation: -rotation
})
}));
});
return styles;
};
var vector = new ol.layer.Vector({
source: source,
style: styleFunction
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
map.addInteraction(new ol.interaction.Draw({
source: source,
type: 'LineString',
freehand:true
}));
</script>
</body>
</html>
网友评论