美文网首页
Openlayers 实例-点聚合

Openlayers 实例-点聚合

作者: 写前端的大叔 | 来源:发表于2020-02-17 13:26 被阅读0次

    如果在地图上加载海量点时,当地图的zoom值越小时,地图上的点越密,密密麻麻的点全部叠加在了一起,看着不是那么友好,在Openlayers中提供了点聚合的功能,既当zoom值越小时,不显示所有的点,而只是显示部分点,并且在点上面显示一个数字,用于展示该点的周围一共有多少个点,当zoom变大时,数字也随之减少,周边的点将分离一些出来,效果如下所示:

    点聚合.png

    这主要是使用了Openlayers中的ol/source/Cluster,可以为Cluster对象设定一个distance值,用来限制之间最小的像素距离。具体用法如下所示,为了方便以后复用,单独写成了一个工具类:

    class ClusterUtil{
        constructor(map,features,distance){
            this.map = map//地图
            this.features = features//要素列表
            this.distance = distance//最小距离
            this._init()
        }
    
        //初始化
        _init(){
            //创建矢量图层
            this.vectorLayer = LayerUtil.vectorLayer()
            this.map.addLayer(this.vectorLayer)
            //创建矢量数据源
            var source = new ol.source.Vector({
                features: this.features
            });
              
            //创建聚合对象并设置数据源和距离
            var clusterSource = new ol.source.Cluster({
                distance: parseInt(this.distance, 10),
                source: source
            });
            this.clusterSource = clusterSource
            //为图层设置聚合数据源
            this.vectorLayer.setSource(clusterSource)
            var styleCache = {};
            //设置样式
            this.vectorLayer.setStyle(function(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;
              })
        }
    
        //动态修改距离
        setDistance(distance){
            this.distance = distance;
            this.clusterSource.setDistance(parseInt(distance.value, 10));
        }
    }
    

    个人博客

    相关文章

      网友评论

          本文标题:Openlayers 实例-点聚合

          本文链接:https://www.haomeiwen.com/subject/wzsbfhtx.html