You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Fancybox 5实现点击Leaflet标记显示图片并分组所有图片

实现Fancybox图片分组与前后切换

核心思路是先把所有GeoJSON要素对应的图片数据提前整理成Fancybox可识别的分组数组,点击标记时定位到对应数组项打开,这样就能利用Fancybox自带的分组切换功能。

修改后的完整代码:

// 提前声明全局数组存储所有Fancybox图片项
let fancyboxItems = [];

function onMouseFancybox(feature, layer) {
    // 根据uuid找到当前图片在分组中的索引
    const itemIndex = fancyboxItems.findIndex(item => item.feature.properties.uuid === feature.properties.uuid);
    
    // 打开分组相册,从当前点击的图片开始
    Fancybox.show(fancyboxItems, {
        startIndex: itemIndex
    });

    layer.setStyle({fillColor: "#ff0000", color: "#ff0000"});
    console.log(feature.properties.uuid);
}

// 加载GeoJSON数据
geojsonFeatureCamera = <?php echo json_encode($geojsonc)?>;

// 预处理所有图片,生成Fancybox分组数组
geojsonFeatureCamera.features.forEach(feature => {
    const foto = `images/${feature.properties.uuid}.jpg`;
    const tijd = feature.properties.timestamp.replace('T', ' ');
    const caption = `${tijd}<br>`;
    
    fancyboxItems.push({
        src: foto,
        caption: caption,
        feature: feature // 关联对应的要素,方便后续匹配
    });
});

// 初始化GeoJSON图层
var geojsonc = L.geoJSON(geojsonFeatureCamera, {
    pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, geojsonMarkerOptionsCamera);
    },
    onEachFeature: function(feature, layer) {
        layer.on('click', function(e) {
            onMouseFancybox(feature, layer);
        });
    }
});

关键修改说明:

  1. 提前生成分组数组:遍历所有GeoJSON要素,把每个要素对应的图片地址、标题都存入fancyboxItems数组,同时关联对应的要素对象,方便点击时快速定位。
  2. 点击时打开分组:不再单独展示单张图片,而是调用Fancybox.show()传入整个分组数组,并通过startIndex指定从当前点击的图片开始展示,这样Fancybox会自动显示前后切换按钮。
  3. 变量规范:改用模板字符串和const/let声明变量,避免全局作用域污染。

内容的提问来源于stack exchange,提问作者Derko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 17:04:52