2017-04-05 45 views
0

因此,我使用OpenLayers3示例here,它工作正常,但我不想在每一行上繪製箭頭。只有第一個被繪製的。這是我現在的風格功能。在OpenLayers中傳遞到樣式函數的第一行上繪製箭頭3

navigationLineStyleFunction: function(feature) { 
    var geometry = feature.getGeometry(); 
    var lineColor = '#c1005d' 
    var styles = [ 
     new ol.style.Style({ 
      stroke: new ol.style.Stroke({ 
       //this can accept rgba colors to hide the lines 
       color: lineColor, 
       width: 6 
      }) 
     }) 
    ]; 
    geometry.forEachSegment(function(start, end, sexting) { 
     var dx = start[0] - end[0]; 
     var dy = start[1] - end[1]; 
     var rotation = Math.atan2(dy, dx); 
     // arrows 
     styles.push(new ol.style.Style({ 
      geometry: new ol.geom.Point(start), 
      image: new ol.style.Icon({ 
       src: 'https://openlayers.org/en/v4.0.1/examples/data/arrow.png', 
       anchor: [0.75, 0.5], 
       rotateWithView: true, 
       rotation: -rotation 
      }) 
     })); 
    }); 

    return styles; 
} 

的問題是與forEachSegment()我想,卻找不到一個函數,只有抓住了第一個。我試圖通過將.push()包裝在一張if聲明中來檢查styles[]的長度,但沒有奏效。我也嘗試用.once()替換forEachSegment(),但那不起作用。

回答

1

而不是使用forEachSegment方法編寫自定義代碼來從幾何中獲取前2個座標,然後在該情況下爲該線段應用樣式。 由於forEachSegment將爲每個段調用方法的回調,同時導致不必要的循環。

我從Openlayers網站上抽取了一個樣本來證明這一點。

修復:

 var coords = geometry.getCoordinates();// Gets all the coordinates 
     var start = coords[0];//First Coordinate 
     var end = coords[1];//Second Coordinate 

     // Rest of the code 
     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: 'https://openlayers.org/en/v4.0.1/examples/data/arrow.png', 
      anchor: [0.75, 0.5], 
      rotateWithView: true, 
      rotation: -rotation 
     }) 
     })); 

看這個plunckr link