问题描述
- esri-leaflet以插件(plugins)形式,直接在前端提供了要素图层的自动聚合功能,即
esri.cluster.Featurelayer
- 在react环境下,
esri.cluster.Featurelayer
的使用与直接引入CDN有一些使用的细节差异
环境准备
- 安装lealet/esri-leaflet
操作步骤省略
- 安装esri-leaflet-cluster插件
npm install esri-leaflet-cluster leaflet.markercluster
注意:因为
esri.cluster.Featurelayer
是基于leaflet.markercluster
进行扩展开发的。故而安装时,两个包都需要安装。后者本身不是leaflet的官方组件,其实也是第三方扩展的,具体使用细节参考,https://github.com/Leaflet/Leaflet.markercluster
- 引入
esri.cluster.Featurelayer
和leaflet.markercluster
的API和CSS样式文件支持
import React, { useEffect } from 'react';
import L from "leaflet"
import * as esri from "esri-leaflet"
import * as markercluster from "leaflet.markercluster"
import * as cluster from "esri-leaflet-cluster"
import "leaflet.markercluster/dist/MarkerCluster.Default.css"
注意:若未引入
leaflet.markercluster
则编译运行后,浏览器很有可能报如下错误,主要就是基础类找不到的原因
TypeError: Object(…) is not a function
21 | this._layers = {};
22 | this._leafletIds = {};
23 |
> 24 | this.cluster = markerClusterGroup(options);
| ^ 25 | this._key = 'c' + (Math.random() * 1e9).toString(36).replace('.', '_');
实例代码
import React, { useEffect } from 'react';
import L from "leaflet"
import * as esri from "esri-leaflet"
import * as markercluster from "leaflet.markercluster"
import * as cluster from "esri-leaflet-cluster"
import "leaflet.markercluster/dist/MarkerCluster.Default.css"
function ClusterFeatureLayer(props) {
useEffect(()=>{
//对于clusterFeatureLayer必须设置maxZoom属性,否则编译会出错
let map = L.map("clusterfeaturelayer_map", { maxZoom: 14}).setView([29.776,106.308],10)
let layer = cluster.featureLayer({
url: "http://localhost:6080/arcgis/rest/services/02_Tky_GDCGK/FeatureServer/4",
pointToLayer: function (geojson, latlng) {
return L.circleMarker(latlng, 2, {
color: "#2D84C8"
});
}
})
layer.addTo(map)
},[])
return (
<div id="clusterfeaturelayer_map" style={{ width: "100%", height: "800px" }}></div>
);
}
export default ClusterFeatureLayer;
代码说明
- import的内容一定要完整,否则编译会出现各种奇怪的错误
- 添加了聚集图层的map一定要设置
maxZoom
属性,否则会引起Uncaught Map has no maxZoom specified
而导致地图不能加载TypeError: Cannot read property '_addChild' of undefined
- 聚集功能是完全基于前端实现展示层实现的,因此不需要对后台的FS有任何的特殊设置
- 一定要分清
esri.cluster.Featurelayer
和leaflet.markercluster
的职责范围:- esri.cluster.Featurelayer使用来解析Arcgis-FS并转为未leaflet的聚集图层
- leaflet.markercluster是对聚集效果、聚集参数进行设置与修改的
- 因为
esri.cluster.Featurelayer
继承扩展自leaflet.markercluster
因此,前者可以使用后者所提供的各种函数接口或config参数