在地图上显示点数据是最常用的地图展示功能之一,但是如果很多点在地图上显示,或造成密密麻麻的一片,无法正常看清楚,这个时候,一般有两种解决方案,一种是根据数据重要程度进行标注,重要的显示大一些,不重要的显示小点,比如百度地图就是这样的;另一种方法是使用聚合,让相邻的点聚合成一个点,也能解决这个问题。

  使用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);

});

   

  完整js源代码:http://dataxiu.com/xius/www/admin/yl/map2d.js