2016-02-26 21 views
0

这是非常相似,我的现实生活中的应用程序的代码示例,计算平均值:的OpenLayers 3个集群的优化 - 如何避免每次

var count = 20000; 
var features = new Array(count); 
var e = 4500000; 
var pointStyle = new ol.style.Style({ 
    image: new ol.style.Circle({ 
    fill: new ol.style.Fill({color: "red"}), 
    radius: 6, 
    snapToPixel: true, 
    }), 
}); 
for (var i = 0; i < count; ++i) { 
    var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; 
    features[i] = new ol.Feature({ 
    geometry: new ol.geom.Point(coordinates), 
    labelPoint: new ol.geom.Point(coordinates), 
    name: Math.random() 
    }); 
    features[i].setStyle(pointStyle); 
} 

var source = new ol.source.Vector({ 
    features: features 
}); 

var clusterSource = new ol.source.Cluster({ 
    distance: 40, 
    source: source 
}); 

var styleCache = {}; 
var clusters = new ol.layer.Vector({ 
    source: clusterSource, 
    style: function(feature, resolution) { 
     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: avg(feature.get('features')), 
      fill: new ol.style.Fill({ 
      color: '#fff' 
      }) 
     }) 
     })]; 
    return style; 
    } 
}); 

var raster = new ol.layer.Tile({ 
    source: new ol.source.MapQuest({layer: 'sat'}) 
}); 

var raw = new ol.layer.Vector({ 
    source: source 
}); 

var map = new ol.Map({ 
    layers: [raster, clusters], 
    renderer: 'canvas', 
    target: 'map', 
    view: new ol.View({ 
    center: [0, 0], 
    zoom: 2 
    }) 
}); 

function avg(features){ 
    var temp = 0; 
    features.forEach(function(val){ 
    temp += val.get('name') 
    }); 
    temp = temp/features.length; 
    return temp; 

https://jsfiddle.net/wydo007p/

这是非常相似的代码我有,除了我有更多的功能。当你放大到最大时,它的工作速度相当快,但是当你从最大值缩小时,需要很长的时间才能重新计算所有的平均值。

我真的需要这更加优化,我慢慢地运行的想法。

我想我需要沿着these行的东西,但我不能有大小idetificator,因为不是所有的与同尺寸的簇都会有相同的平均值。

+0

你有没有发现任何解决你的问题?我遇到了一些严重的集群性能问题,我不明白它是如何修复的...... –

回答

1

风格功能不是做昂贵的计算的好地方,因为它被称为非常频繁(如你发现了)。创建群集功能时,最好只计算一次平均值。要做到这一点,你可以注册一个监听到源的featureadded事件:

clusterSource.on('addfeature', function(e) { 
    e.feature.set('avg', avg(e.feature.get('features'))); 
}); 

在风格功能,可以创建一个静态的风格:

var 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: '', 
    fill: new ol.style.Fill({ 
     color: '#fff' 
    }) 
    }) 
}); 

这种风格有一个空的文本(“” ),我们将在集群层的样式功能设置:

style: function(feature, resolution) { 
    var avg = feature.get('avg'); 
    style.getText().setText(avg); 
    return style; 
} 

工作例如:http://jsfiddle.net/tr91j6Lr/4/