OpenLayers官方示例詳解六之線串箭頭樣式(LineString Arrows)
阿新 • • 發佈:2018-12-14
目錄
一、示例簡介
為每一個線串(LineString)的子線段繪製箭頭。
二、程式碼詳解
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>LineString Arrows</title> <link href="ol_v5.0.0/css/ol.css" rel="stylesheet" type="text/css" /> <script src="ol_v5.0.0/build/ol.js" type="text/javascript"></script> </head> <body> <div id="map"></div> <script> // Open Street Map地圖 var raster = new ol.layer.Tile({ source: new ol.source.OSM() }); // 用於繪製線串的向量圖層源 var source = new ol.source.Vector(); // 用於繪製線串的向量圖層 var vector = new ol.layer.Vector({ source: source, style: styleFunction }); var map = new ol.Map({ target: 'map', layers: [ raster, vector ], view: new ol.View({ center: [-11000000, 4600000], zoom: 4 }) }); // 新增一個繪製線串的控制元件 map.addInteraction(new ol.interaction.Draw({ source: source, type: 'LineString' })); // 用於設定線串所在的向量圖層樣式的函式 var styleFunction = function(feature){ var geometry = feature.getGeometry(); var styles = [ new ol.style.Style({ // 線串的樣式 stroke: new ol.style.Stroke({ color: '#FC3', 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); // 獲取子線段的角度(弧度) //arrows styles.push(new ol.style.Style({ // 與線串的各個子線段對應的樣式 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; }; </script> </body> </html>
三、總結
這個示例不太難。。不總結了