在地圖上顯示點(diǎn)數(shù)據(jù)是最常用的地圖展示功能之一狈网,但是如果很多點(diǎn)在地圖上顯示,或造成密密麻麻的一片笨腥,無法正惩夭福看清楚,這個(gè)時(shí)候脖母,一般有兩種解決方案士鸥,一種是根據(jù)數(shù)據(jù)重要程度進(jìn)行標(biāo)注,重要的顯示大一些谆级,不重要的顯示小點(diǎn)烤礁,比如百度地圖就是這樣的;另一種方法是使用聚合哨苛,讓相鄰的點(diǎn)聚合成一個(gè)點(diǎn)鸽凶,也能解決這個(gè)問題。
使用openlayers 3 地圖組件比較容易解決這個(gè)問題建峭,關(guān)鍵是??ol.source.Cluster 對(duì)象玻侥,這個(gè)對(duì)象有兩個(gè)參數(shù),一個(gè)是聚合距離亿蒸,一個(gè)是原始的點(diǎn)數(shù)據(jù)凑兰。代碼片段如下:
1:初始化ol3 map對(duì)象:
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 ?//初始坐標(biāo)范圍和放大級(jí)別。
})])
});
2:準(zhǔn)備Json數(shù)據(jù)并添加:
$.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;
});
// 添加到矢量數(shù)據(jù)源
var vectorSource = new ol.source.Vector({
features : features
});
//添加到聚合數(shù)據(jù)源边锁,如果不用這個(gè)的話姑食,就會(huì)得到許多的點(diǎn)
var clusterSource = new ol.source.Cluster({
distance: 40,
source: vectorSource
});
//設(shè)定圖層數(shù)據(jù)源
tmpLayer.setSource(null);
tmpLayer.setSource(clusterSource);
tmpLayer.setStyle(createStyle);
that.setLayerVisible(options.id, true);
});