项目作者: universezy

项目描述 :
【Web Demo】基于Openlayers3的LineString使用demo。
高级语言: JavaScript
项目地址: git://github.com/universezy/Openlayer3-LineString.git
创建时间: 2017-06-17T08:27:28Z
项目社区:https://github.com/universezy/Openlayer3-LineString

开源协议:

下载


Openlayer3学习心得之LineString

前言

关于LineString,官方的示例给的是鼠标画点,自动连线,并添加箭头(LineString Arrows示例),而在我们实际应用中,往往需要手动录入标记点,然后进行连线并添加箭头,下面就分享我使用LineString的过程:


1. 首先是静态数据的:

  • 先准备一个source图层用来画点:
  1. var source = new ol.source.Vector();
  • 然后是录入标记点的信息,所有点共同构成一个feature:
  1. var feature = new ol.Feature({
  2. geometry:new ol.geom.LineString(coordinate1,coordinate2,coordinate3,coordinate4......)
  3. });
  • 然后把feature添加到source里:
  1. source.addFeature(feature);
  • 接下来准备一个图层用来画线和箭头:
  1. var vector = new ol.layer.Vector({
  2. source: source,
  3. style: myStyle
  4. });
  • 这里的myStyle函数返回的是对线和箭头样式设置的style:
  1. var myStyle = function(feature) {
  2. var geometry = feature.getGeometry();
  3. var styles = [
  4. new ol.style.Style({
  5. fill: new ol.style.Fill({
  6. color: '#0044CC'
  7. }),
  8. stroke: new ol.style.Stroke({
  9. lineDash:[1,2,3,4,5,6],
  10. width: 3,
  11. color: [255, 0, 0, 1]
  12. })
  13. })
  14. ];
  15. geometry.forEachSegment(function(start, end) {
  16. var arrowLonLat = [(end[0]+start[0])/2,(end[1]+start[1])/2];
  17. var dx = end[0]- start[0];
  18. var dy = end[1] - start[1];
  19. var rotation = Math.atan2(dy, dx);
  20. styles.push(new ol.style.Style({
  21. geometry: new ol.geom.Point(arrowLonLat),
  22. image: new ol.style.Icon({
  23. src: 'res/arrow.png',
  24. anchor: [0.75, 0.5],
  25. rotateWithView: true,
  26. rotation: -rotation
  27. })
  28. }));
  29. });
  30. return styles;
  31. };

函数里上面的styles就是线的样式设置,lineDash是设置虚线,下面的geometry是设置的箭头,需要计算旋转角度,我的箭头图片是一个朝右的三角形,arrowLonLat得到的线的起点和终点的中点。
然后把地图层和这个linestring的图层vector一起加到map的layers里就完成了。


2. 接下来说动态添加新的标记点:

  • geometry可以设为全局变量:
  1. var geometry = new ol.geom.LineString();
  • 然后使用appendCoordinate添加点:
  1. geometry.appendCoordinate(ol.proj.transform(newPoint, 'EPSG:4326', 'EPSG:3857'));

geometry设置好后,feature也就完成了,然后把之后的几个步骤中的变量更新一下就完成了。


3. 效果图:


4. 在线体验:

Openlayers3-LineString on-line