openLayers2点聚合常用操作

1、地图初始化及响应事件

	map = new Geo.View2D.Map("mapContainerId", {   
		eventListeners: {
			'zoomend': zoomendF
		}
	})
	// 地图注册事件的另一种方式
	map.events.register('moveend', this, moveendF)
	
	// 基础图层
	let baseLayer = new OpenLayers.Layer('baseLayer', {
		maxResolution: (360 / 256) / Math.pow(2, 10),
	    minResolution: (360 / 256) / Math.pow(2, 19),
	    maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90),
	    displayInLayerSwitcher: false,
	    isBaseLayer: true,
    })
	map.addControl(new Geo.View2D.Control.MousePosition())
	map.addLayer(baseLayer)

2、点聚合、描点、点及聚合点自定义图标

	clusterLayer = new OpenLayers.Layer.Vector('clusterLayer', {
		strategis: [strategy],
		styleMap: new OpenLayers.StyleMap({
			default: style,
			select: {}
		})
	})
	for (let i = 0; i < list.length; i++) {
		let point3 = new Geo.Geometry.Point(list[i].lon, list[i].lat);
        let geometry = point3.clone();
        // 第二个参数,将点信息放到cluster的attributes属性中
        let pointFeature3 = new Geo.Feature.Vector(geometry, list[i]); 
	}
	// strategy定义
	let strategy = new Geo.Strategy.Cluster({
        distance: 40,
        active: true
    })
 	strategy.distance = 50 || strategy.distance;
 	strategy.threshold = 1 || strategy.threshold;

	// style定义
	style = new OpenLayers.Style({
		pointRadius: '${getPointRadius}',
		label: '${getLabel}',
		externalGraphic: '${getIcon}',   // 点、聚合点图标
		graphicHeight: '${getHeight}',  // 图标宽高,可根据实际情况处理
		graphicWidth: '${getWidth}'
		...
		其他属性
		...
	}{
		context: {
			getPointRadius: function(feature) {
				let pix = 10;
                if (feature.cluster) {
                    pix = Math.min(feature.attributes.count, 7) + 10;
                }
                return pix;
			},
			getLabel: function(feature) {
				// 聚合点展示点个数,单个点则不展示
				return feature.attributes.count > 1 ? feature.attibutes.count : ''
			},
			getIcon: function(feature) {
				if(feature.attributes.count > 1) {
					return '单个点图标路径'
				} else {
					return '聚合点图标'
				}
			}
		}
	})

3、鼠标悬浮展示弹窗

hoverSelect = new OpenLayers.Control.SelectFeature(clusterLayer, {
	hover: true,
	highlightOnly: true
})
map.addControl(hoverSelect)
hoverSelect.activate()
let popup = null
hoverSelect.events.on({
	'featurehighlighted': function(data){
		let {feature} = data
        if (feature.popup) {
             return
         }
		let content = '自定义内容'
		popup = new OpenLayers.Popup("chicken",
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(280, 140),
            content,
            null,
            true,
            onPopupClose
        )
        feature.popup = popup
        map.addPopup(popup)
	},
	'featureunhighlighted': function (event) {
         let feature = event.feature
         if (feature.popup) {
             map.removePopup(feature.popup);
             feature.popup.destroy()
             delete feature.popup
         }
         if (feature.attributes && feature.attributes.count == 1) {
             map.removePopup(popup)
         }
     }
})


function onPopupClose() {
	 hoverSelect.unselectAll()
}

4、鼠标点击展示弹窗

iSelect = new OpenLayers.Control.SelectFeature(clusterLayer, {
	 clickout: true,
     toggle: false,
     multiple: false,
     hover: false,
     toggleKey: "ctrlKey", // ctrl key removes from selection
     multipleKey: "shiftKey", // shift key adds to selection,
     box: false
})
map.addControl(hoverSelect)
iSelect.activate()
clusterLayer.events.on({
	featureselected: function(event) {
		 if (feature.popup) {
            map.removePopup(feature.popup);
             feature.popup.destroy();
             delete feature.popup;
         }
         // 打开弹窗,操作同上
	},
	featureunselected:  function() {
		// 关闭弹窗,操作同上
	}
})

以下是使用OpenLayers实现聚合的完整代码示例。 HTML文件: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>OpenLayers Point Clustering Example</title> <link rel="stylesheet" href="https://openlayers.org/en/v6.5.0/css/ol.css" type="text/css"> <style> .map { height: 500px; width: 100%; } </style> </head> <body> <div id="map" class="map"></div> <script src="https://openlayers.org/en/v6.5.0/build/ol.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4-src.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/turf.js/5.1.6/turf.min.js"></script> <script src="cluster.js"></script> </body> </html> ``` JavaScript文件(cluster.js): ```javascript // 聚合半径 var radius = 40; // 创建地图 var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([0, 0]), zoom: 2 }) }); // 创建一个聚合层 var clusterLayer = new ol.layer.Vector({ source: new ol.source.Vector(), style: function(feature) { var size = feature.get('features').length; 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: size.toString(), fill: new ol.style.Fill({ color: '#fff' }) }) }); return style; } }); map.addLayer(clusterLayer); // 加载数据并进行聚合 var url = 'data.geojson'; fetch(url).then(function(response) { return response.json(); }).then(function(json) { var features = new ol.format.GeoJSON().readFeatures(json); var clusters = getClusters(features, radius); clusterLayer.getSource().addFeatures(clusters); }); ``` 在上述代码中,我们首先创建了一个地图,并添加了一个OSM图层。然后创建了一个聚合层,并将其添加到地图中。接着,我们从一个GeoJSON文件中加载数据,并调用getClusters()函数对数据进行聚合。最后,我们将聚合后的数据添加到聚合层的源中。 请注意,在这个示例代码中,我们使用了turf.js库来计算两个之间的距离,以便进行聚合。如果您不想使用turf.js,可以使用OpenLayers的ol.Sphere类来计算距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值