如何按设计修改ESRI的popupTemplate,React中点击图标不显示弹窗如何解决
ESRI popupTemplate自定义及React环境点击无弹窗解决方案
自定义popupTemplate实现目标效果
你可以直接通过组合fields类型内容块和自定义HTML的text类型内容块实现字段展示+底部图标操作栏的需求,配置参考如下:
const popupTemplate = { title: "{Name}", // 弹窗顶部标题直接绑定字段值 content: [ { type: "fields", fieldInfos: [ { fieldName: "Name", label: "名称" }, { fieldName: "Owner", label: "所有者" }, { fieldName: "Length", label: "长度" } ] }, { type: "text", text: `<div class="icontain"> <a class="ic"><i class="bi bi-star"></i></a> <a class="ic"><i class="bi bi-geo-alt-fill"></i></a> </div>` } ] }
如果需要给自定义图标加点击交互,可监听弹窗的显示事件绑定逻辑:
view.popup.watch("visible", (visible) => { if (visible) { // 获取当前选中的要素属性 const selectedFeature = view.popup.selectedFeature; // 给自定义图标绑定点击事件 document.querySelector(".bi-star").addEventListener("click", () => { // 执行收藏逻辑 }) } })
自定义样式直接写在全局CSS中即可,组件内的作用域样式无法作用于弹窗元素。
React环境点击无弹窗问题修复
你遇到的点击图标不弹出弹窗是以下几个问题导致的,逐一修改即可:
- 自定义点未配置弹窗模板:你只给远程FeatureLayer配置了popupTemplate,但是
displayLocation方法里手动创建的Graphic实例没有设置popupTemplate属性,点击这类自定义点自然不会触发弹窗。 - 字段名带多余空格:配置fieldInfos时写的
fieldName: "Name "尾部多了空格,和图层实际字段名不匹配会导致字段值无法正常显示。 - 自定义HTML语法错误:你写的
<div class=\"icontain\"></>标签闭合错误,会导致自定义内容渲染异常。 - 提前覆盖DOM引用:你在view.when里把
mapDiv.current赋值为view实例,会导致原DOM引用丢失,属于隐性错误。
修复后的核心代码参考:
useEffect(() => { if (mapDiv.current) { esriConfig.apiKey = process.env.ARCGIS_API; const map = new Map({ basemap: 'arcgis-light-gray' }); const view = new MapView({ center: [123.5504, 12.3574], container: mapDiv.current, map: map, zoom: 13, popup: { enabled: true } // 显式开启弹窗能力 }); // 统一定义通用弹窗模板 const commonPopupTemplate = { title: "{Name}", content: [ { type: "fields", fieldInfos: [ { fieldName: "Name", label: "名称" }, { fieldName: "Owner", label: "所有者" }, { fieldName: "Length", label: "长度" } ] }, { type: "text", text: `<div class="icontain"> <a class="ic"><i class="bi bi-star"></i></a> <a class="ic"><i class="bi bi-geo-alt-fill"></i></a> </div>` } ] } view.when(() => { setMapView(view); // 统一绑定弹窗图标点击事件 view.popup.watch("visible", (visible) => { if (visible) { // 此处添加图标点击逻辑 } }) }); const featureLayer = new FeatureLayer({ url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/ArcGIS/rest/services/Beverly%20Hills%20Trees%20By%20Block/FeatureServer/0", popupTemplate: commonPopupTemplate, outFields: ["*"] }); map.add(featureLayer); } }, []); const displayLocation = (locations) => { mapView.center = [ locations.data[0].geoCode.longitude, locations.data[0].geoCode.latitude, ]; locations.data.map((location) => { const point = new Graphic({ geometry: { latitude: location.geoCode.latitude, longitude: location.geoCode.longitude, type: 'point', }, symbol: LocationPin, // 传入点对应的属性字段 attributes: { Name: location.name, Owner: location.owner, Length: location.length }, popupTemplate: commonPopupTemplate // 给自定义点也绑定弹窗模板 }); mapView.graphics.add(point); }); };
内容的提问来源于stack exchange,提问作者user15404864
相关产品推荐
相关产品推荐

