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

Google Maps MarkerClustererPlus缩小时关闭聚合标记InfoWindow并触发自定义函数问询

解决方案

问题本质

  • 自动弹窗的核心原因是InfoWindow和标记的绑定关系没有被主动清除:MarkerClusterer聚合标记时仅临时将标记从地图移除,InfoWindow会保留和标记的关联,当标记重新回到地图时就会自动弹出
  • 原有代码的循环事件绑定存在var变量提升的作用域问题,导致map_changed监听无法正确匹配对应标记,遍历集群的逻辑也存在时机误差

修复方案

直接替换原有addMarkers函数即可,已经集成了InfoWindow彻底关闭逻辑,你可以在标注// 此处调用你的自定义函数的位置加入你要执行的自定义逻辑:

function addMarkers() 
{
    infowindow = new google.maps.InfoWindow();
    // 监听InfoWindow手动关闭事件,主动清除锚点绑定
    google.maps.event.addListener(infowindow, 'closeclick', function() {
        infowindow.setAnchor(null);
        curMark = null;
        prev_infowindow = false;
    });

    var markers = [];

    for (let i = 0; i < WeatherStations.length; i++) {
        var latLng = new google.maps.LatLng(WeatherStations[i].Latitude, WeatherStations[i].Longitude)

        var marker = new google.maps.Marker({
            position: latLng,
            map: map,
            visible: true,
            zIndex: 10,
            stationData: WeatherStations[i] // 可将站点数据绑定到marker上方便后续自定义逻辑调用
        });

        var content = "<div id='" + WeatherStations[i].stn + " '> <div class='scrollfix'><b>" + WeatherStations[i].StationName + "</b>";

        google.maps.event.addListener(marker, 'click', (function(marker, content, infowindow) {
            return function() {
                curMark = this;
                // 关闭已打开的InfoWindow
                if (prev_infowindow) {
                    prev_infowindow.close();
                }

                prev_infowindow = infowindow;

                infowindow.setContent(content);
                infowindow.open(map, marker);
            };
        })(marker, content, infowindow));

        markers.push(marker);
    }

    var zoom = null;
    var size = null;
    var style = 0;

    markerClusterer = new MarkerClusterer(map, markers, {
        maxZoom: zoom,
        gridSize: size,
        styles: styles[style]
    });

    // 监听集群聚合完成事件
    google.maps.event.addListener(markerClusterer, 'clusteringend', function() {
        // 无当前打开的标记则直接返回
        if (!curMark || !infowindow) return;
        // 检查当前标记是否在地图上,不在地图上说明已被收入集群
        if (!curMark.getMap()) {
            try {
                infowindow.close();
                infowindow.setAnchor(null); // 关键:清除InfoWindow和标记的绑定关系
                prev_infowindow = false;
                curMark = null;
                // 此处调用你的自定义函数
            } catch (e) {}
        }
    });
}

效果验证

缩小地图标记被聚合时,会直接关闭InfoWindow并清除绑定,再次放大地图时标记显示不会自动弹出InfoWindow,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:54:05