2017-02-13 145 views
0

我從第三方API提取數據,該數據給出了緯度/經度座標以及點的狀態。我目前能夠在第一次迭代中成功繪製點併爲他們提供正確的狀態。但是,如果狀態發生變化,我需要每3秒鐘更新一次自己的樣式。我試過使用mySource.changed(),但它沒有奏效。我看了一遍又一遍,找不到解決方案,儘管這似乎並不是一件困難的事情。更新OpenLayers中的功能樣式3

我也嘗試過clear()我的源碼每隔3秒,但隨後矢量圖層'閃爍',我需要它無縫地更新。我也嘗試刪除/重新添加整個矢量圖層。我需要使用樣式函數嗎?或功能覆蓋?爲什麼我不能在Google地圖或傳單中覆蓋樣式?

我的風格

var takenStyle = new ol.style.Style({ 
    image: new ol.style.Icon({ 
     src: '../_images/redMark.png', 
     scale: .2 
    }) 
}); 
var openStyle = new ol.style.Style({ 
    image: new ol.style.Icon({ 
     src: '../_images/greenMark.png', 
     scale: .2 
    }) 
}); 
var unsureStyle = new ol.style.Style({ 
    image: new ol.style.Icon({ 
     src: '../_images/yellowMark.png', 
     scale: .2 
    }) 
}); 

我如何分配的樣式/功能

if ((data.scopes[i].parking_spot.status === true)) { 
var feature = new ol.Feature({ 
    geometry: new ol.geom.Point(ol.proj.transform(pointCoords, 'EPSG:4326', 'EPSG:3857')) 
}); 
feature.setStyle(takenStyle); 
feature.setId(i); 
pointSource.addFeature(feature); 

UPDATE:使用Navageer·高達的建議下,我能終於想出解決辦法。我創建了第二個函數,並通過迭代功能來更新樣式。

if ((data.scopes[i].parking_spot.occupied === true && data.scopes[i].parking_spot.occupied === lastCheck[i].occupied)) { 
    theFeatures[i].setStyle(takenStyle); 
} 
+0

你嘗試'feature.changed()'方法? [看到它](http://openlayers.org/en/v3.2.0/apidoc/ol.Feature.html?unstable=true#changed) – tfidelis

+0

是的,我試過。似乎沒有發生。我也嘗試在pointSource上使用它。但沒有運氣。我會在設置樣式的if語句中調用我的feature.changed()嗎? –

+0

是的,我認爲是。你能爲我們展示你的所有代碼嗎?我將創建一個jsfiddle並嘗試調試它以更好地幫助您。 – tfidelis

回答

2

要強制每3秒圖層樣式的刷新,你可以這樣做:

window.setInterval(function() { 
    layer.getSource().dispatchEvent('change'); 
}, 3000); 

然而,API支持你想要什麼通過在ol.source.Vector上使用自定義加載函數和在ol.layer.Vector上使用自定義樣式函數,以更簡潔的方式進行操作。它看起來像這樣:

var layer = new ol.layer.Vector({ 
    source: new ol.source.Vector({ 
    loader: function(extent, resolution, projection) { 
     var fetchData = function() { 
     // Fetch data here, add features *without style* to layer.getSource() 
     }; 

     // Fetch data once immediately 
     fetchData(); 

     // re-fetch every 3 seconds 
     window.setInterval(fetchData, 3000); 
    } 
    }), 
    style: function(feature, resolution) { 
    var props = feature.getProperties(); 

    // Psuedo-logic shown here, use your own to determine which style to return 
    if (isTaken) { 
     return takenStyle; 
    } else if (isOpen) { 
     return openStyle; 
    } else { 
     return unsureStyle; 
    } 
    } 
}); 
+0

這爲我工作,並使我的代碼更清潔。謝謝。 –

+0

真棒!很高興我能幫上忙。 –

1

看來您每次更改樣式時都會再次添加相同的功能。您可以爲源做任何

  1. 閱讀功能和更改的功能,風格或
  2. 做source.clear()創建新功能之前,並添加到pointSource。(source.clear刪除所有存在的功能在矢量源)
+0

我正在添加相同的功能,我只想爲它們創建一個功能。如果我改變它,所以我有另一個功能,只更新樣式,我會做一個source.getFeatures([i])。setStyle('whateverstyle')?然後在我的矢量圖層上運行刷新?我現在可以通過每三秒在函數開始處運行clear()函數來實現它,但是這會導致矢量圖層「閃爍」,並且我需要它無縫。 –

+0

此外,我相信我嘗試updateParams(),我不認爲你可以在矢量圖層上使用它。 –

+0

@AustinTruex source.getFeatures([i])。setStyle('whateverstyle')?嘗試遍歷所有功能並設置樣式。它應該工作 –