2017-02-13 88 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')?尝试遍历所有功能并设置样式。它应该工作 –