OpenLayers给地图添加标记点并聚合

OpenLayers给地图添加标记点并聚合

徐徐
前端
发布于2024-10-17 10:25:11
🌺前言
OpenLayers给地图添加标记点并聚合的简化步骤

1.准备好每个标记点经纬度

2.构造标记点图层

typescript
        const features = list.map(item => {
            const iconFeature = new Feature({
                geometry: new Point(fromLonLat(item.geometry.coordinates)),
                name: item.properties.deviceName,
                attribute: {
                    ...item.properties,
                    coordinate: fromLonLat(item.geometry.coordinates),
                    type: "marker",
                }
                //名称属性
            });
            return iconFeature
        })

        //矢量标注的数据源
        const vectorSource = new Vector({
            features,
            wrapX: false
        });
        const clusterSource = new Cluster({
            distance: 30, // 超过多少开始聚合
            source: vectorSource,
        });
   const layer new VectorLayer({
                    source: vectorSource,
                    zIndex:1 ,
                    visible:true,
                    className: '',
                    style: getSelftClusterStyle()
                });
                
       /**
     * 聚合点的样式
     * @param type 
     * @returns 
     */
    const getSelftClusterStyle = () => {
        return function (feature: any) {
            const styleCache: any[] = []
            const size = feature?.get("features").length;
            let style = styleCache[size];
            if (!style) {
                style = [
                    new Style({
                        image: new Icon({
                            anchor: [0.5, -16],
                            anchorOrigin: "top-right",
                            anchorXUnits: "fraction",
                            anchorYUnits: "pixels",
                            offsetOrigin: "top-right",
                            scale: 0.2,
                            opacity: 1, //透明度
                            src:  markerRed  //图标的URL
                        }
                        ),
                        text: new Text({
                            font: 'normal 18px',    //文字样式
                            text: size > 1 ? size.toString() : feature.get('features')[0].get('name'),
                            fill: new Fill({
                                color: '#E98F36',
                            }),

                        }),
                    }),
                ];
                styleCache[size] = style;
            }
            return style;
        }
    }

3.将图层添加到地图

typescript
map.addLayer(layer)

目录

文章最后更新于 2024-10-17 10:25:11
留言
暂无数据

~~空空如也