如何将ArcGIS Basemap Gallery控件改为点击图标触发的展示形式?
改造ArcGIS JavaScript API底图库为点击触发式组件
可以通过隐藏默认控件容器+自定义触发按钮+切换显示状态的方式实现,以下是具体实现方案:
1. HTML结构准备
添加触发按钮和底图库的承载容器,默认隐藏容器:
<!-- 地图视图容器 --> <div id="viewDiv" style="width: 100%; height: 100vh;"></div> <!-- 底图切换触发按钮 --> <button id="basemapToggleBtn" class="basemap-toggle-btn"> <!-- 这里可以替换成你需要的图标,比如地图图标SVG --> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path> <circle cx="12" cy="12" r="3"></circle> </svg> </button> <!-- 底图库容器,默认隐藏 --> <div id="basemapGalleryContainer" class="basemap-gallery-container"></div>
2. 样式设置
通过CSS控制按钮和容器的位置、显示状态:
.basemap-toggle-btn { position: absolute; top: 18px; right: 18px; width: 42px; height: 42px; border: none; border-radius: 6px; background: #ffffff; cursor: pointer; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); z-index: 101; } .basemap-gallery-container { position: absolute; top: 68px; right: 18px; width: 280px; max-height: 350px; background: #ffffff; border-radius: 6px; box-shadow: 0 3px 12px rgba(0, 0, 0, 0.2); display: none; /* 默认隐藏 */ z-index: 100; overflow-y: auto; } /* 显示容器的类 */ .basemap-gallery-container.show { display: block; }
3. JavaScript逻辑实现
初始化地图、视图和底图库,绑定按钮点击事件切换显示状态,同时支持点击外部关闭:
require([ "esri/widgets/BasemapGallery", "esri/widgets/BasemapGallery/support/PortalBasemapsSource", "esri/Map", "esri/views/MapView" ], function(BasemapGallery, PortalBasemapsSource, Map, MapView) { // 初始化地图 const map = new Map({ basemap: "topo-vector" }); // 初始化地图视图 const view = new MapView({ container: "viewDiv", map: map, center: [-118.805, 34.027], zoom: 13 }); // 初始化底图库,挂载到自定义容器 const basemapGallery = new BasemapGallery({ view: view, source: new PortalBasemapsSource({ portal: { url: "https://www.arcgis.com" } }), container: "basemapGalleryContainer" }); // 获取DOM元素 const toggleBtn = document.getElementById("basemapToggleBtn"); const galleryContainer = document.getElementById("basemapGalleryContainer"); // 点击按钮切换底图库显示/隐藏 toggleBtn.addEventListener("click", () => { galleryContainer.classList.toggle("show"); }); // 点击地图视图其他区域关闭底图库 view.on("click", (event) => { const target = event.target; if (!galleryContainer.contains(target) && target !== toggleBtn) { galleryContainer.classList.remove("show"); } }); });
可选优化
- 可以给容器添加CSS过渡动画,比如
transition: opacity 0.3s ease, transform 0.3s ease;,让显示/隐藏更平滑 - 如果需要更轻量化的触发方式,也可以用ArcGIS JS API的
Popup组件承载底图库,点击按钮打开Popup即可 - 自定义按钮图标可以替换为ArcGIS官方图标库中的资源,保持风格统一
内容的提问来源于stack exchange,提问作者user21045033
相关产品推荐
相关产品推荐

