2015-10-21 17 views
1

如何在Openlayers 3中將集羣層的樣式定義爲ol.style.Style對象而不是函數?如何在沒有樣式函數的情況下動態設置集羣層的樣式

我正在使用僅接受ol.style.Style對象進行造型的庫(ol3-google-maps)。該official cluster example使用樣式功能,在每個集羣特徵的數量動態地添加到它的圖標:

style: function(feature, resolution) { 
    console.log(feature); 
    var size = feature.get('features').length; 
    var style = styleCache[size]; 
    if (!style) { 
    style = [ 
     new ol.style.Style({ 
     image: new ol.style.Circle({ 
      radius: 10, 
      stroke: new ol.style.Stroke({ 
      color: '#fff' 
      }), 
      fill: new ol.style.Fill({ 
      color: '#3399CC' 
      }) 
     }), 
     text: new ol.style.Text({ 
      text: size.toString(), 
      fill: new ol.style.Fill({ 
      color: '#fff' 
      }) 
     }) 
     }) 
    ]; 
    styleCache[size] = style; 
    } 
    return style; 
} 
+0

請澄清一下您的問題。你想要什麼樣的物體?你指的是什麼圖書館? –

+0

Hi Alvin, 在上面的代碼中,style屬性從函數(特徵,分辨率)中取值。我想直接創建ol.style.Style的一個對象,而不是使用該函數。 我正在使用mapgears庫來將谷歌地圖與ol3進行整合: - https://github.com/mapgears/ol3-google-maps 目前,圖書館沒有將功能作爲樣式屬性的值。 – user189107

+0

我不認爲沒有樣式函數的集羣目前可以在ol3中使用。不過,我很樂意聽到更多關於此的信息。 –

回答

1

OL3風格的功能是偉大的,當風格取決於特徵的某些屬性,如子功能的數量一個集羣。沒有其他方式可以在樣式中使用動態屬性。

您可以對羣集層使用不依賴於羣集大小(不顯示功能數量)的通用樣式,如this example

但是,您也可以爲每個要素設置非動態樣式,而不是每個圖層。這種風格可以根據它的屬性來計算,給你一些風格功能的可能性。

This example是不使用普通樣式函數的官方示例的修改。相反,它會監聽羣集源的addfeaturechangefeature事件,並根據其屬性自身的屬性設置樣式(請參閱下面的代碼)。

這不是說這不是一個通用的解決方案或樣式函數的替代品,儘管它對羣集來源應該可以很好地工作。值得注意的是,你失去了基於分辨率生成樣式的可能性。如果該功能被其他圖層使用,則可能不希望將樣式設置爲功能。您還必須考慮性能問題。

var styleCache = {}; 
var styleFunctionIsChangingFeature = false 
var styleFunction = function (evt) { 
    if (styleFunctionIsChangingFeature) { 
     return; 
    } 
    var feature = evt.feature; 
    var size = feature.get('features').length; 
    var style = styleCache[size]; 
    if (!style) { 
     style = new ol.style.Style({ 
      image: new ol.style.Circle({ 
       radius: 10, 
       stroke: new ol.style.Stroke({ 
        color: '#fff' 
       }), 
       fill: new ol.style.Fill({ 
        color: '#3399CC' 
       }) 
      }), 
      text: new ol.style.Text({ 
       text: size.toString(), 
       fill: new ol.style.Fill({ 
        color: '#fff' 
       }) 
      }) 
     }); 
     styleCache[size] = style; 
    } 
    styleFunctionIsChangingFeature = true 
    feature.setStyle(style); 
    styleFunctionIsChangingFeature = false 
}; 

clusterSource.on('addfeature', styleFunction); 
clusterSource.on('changefeature', styleFunction); 
+0

Alvin,非常感謝您的回答。 – user189107

+0

Alvin,你能否刪除我的疑問? 爲什麼style屬性總是定義爲一個數組,但不是直接定義爲ol.style.Style對象? – user189107

+0

它並不總是一個數組。 'ol.Feature'和'ol.layer.Vector'的樣式選項可以是一個單獨的'ol.style.Style',這樣的對象的數組或者返回這樣一個數組的樣式函數。設置靜態樣式時,一個樣式的數組等同於設置沒有數組的樣式。當多個樣式用於相同功能時,樣式陣列很有用。我從答案中刪除了數組。 –

相關問題