在地圖上顯示點數據是最常用的地圖展示功能之一,但是如果很多點在地圖上顯示,或造成密密麻麻的一片,無法正常看清楚,這個時候,一般有兩種解決方案,一種是根據數據重要程度進行標注,重要的顯示大一些,不重要的顯示小點,比如百度地圖就是這樣的;另一種方法是使用聚合,讓相鄰的點聚合成一個點,也能解決這個問題。
使用openlayers 3 地圖組件比較容易解決這個問題,關鍵是??ol.source.Cluster 對象,這個對象有兩個參數,一個是聚合距離,一個是原始的點數據。代碼片段如下:
1:初始化ol3 map對象:
this.ol2d = new ol.Map({
layers: [],//地圖圖層
target: 'map2d',//地圖控件
controls: ol.control.defaults({
attributionOptions:
({
collapsible: false
})
}),
view : new ol.View({
center : ol.proj.transform([ 178.1833, 41.3833 ], 'EPSG:4326', 'EPSG:3857'), zoom : 3 ?//初始坐標范圍和放大級別。
})])
});
2:準備Json數據并添加:
$.getJSON(options.url, function(result) {
var features=[];
$(result).each(function(i, val) {
geom = new ol.geom.Point(ol.proj.transform([ val.lat, val.lng ], 'EPSG:4326', 'EPSG:3857'));
feature = new ol.Feature(geom);
features.push(feature);
feature.data = val;
});
// 添加到矢量數據源
var vectorSource = new ol.source.Vector({
features : features
});
//添加到聚合數據源,如果不用這個的話,就會得到許多的點
var clusterSource = new ol.source.Cluster({
distance: 40,
source: vectorSource
});
//設定圖層數據源
tmpLayer.setSource(null);
tmpLayer.setSource(clusterSource);
tmpLayer.setStyle(createStyle);
that.setLayerVisible(options.id, true);
});