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

技术求助:向Google Maps InfoWindow传递更多信息失败

解决Google Maps InfoWindow无法正确传递数据的问题

看起来你遇到的是循环绑定事件时的闭包作用域陷阱——这确实是个容易踩的小坑,我当初也折腾过好一会儿😅。

问题根源

在你原来的循环里,直接给marker绑定click事件时,事件函数里引用的i是循环的全局变量。当循环结束后,所有marker的点击事件触发时,i已经变成了数组的最后一个索引,所以每次点击都会拿到最后一条数据,而不是对应的那条。

两种快速解决方案

方案1:用封装函数创建独立作用域(兼容所有浏览器)

把创建marker和绑定事件的逻辑拆成一个单独的函数,每次循环传入当前的res项,这样每个函数调用都会生成一个独立的作用域,保存对应的数据:

// 先定义创建marker的函数
function buildMarker(item) {
  const marker = new google.maps.Marker({
    position: new google.maps.LatLng(item.position.lat, item.position.long),
    title: '',
    orderid: item.id,
    map: map,
    icon: icon,
  });

  // 绑定点击事件,直接用item就能拿到当前项的所有数据
  google.maps.event.addListener(marker, "click", function() {
    // 拼接InfoWindow的内容,想用什么字段就用什么
    const infoContent = `
      <div class="info-window">
        <h4>${item.name}</h4>
        <p>订单ID:${item.id}</p>
        <p>日期:${item.date}</p>
      </div>
    `;
    const infoWindow = new google.maps.InfoWindow({ content: infoContent });
    infoWindow.open(map, marker);
  });
}

// 循环调用函数创建marker
for (let i = 0; i < res.length; i++) {
  buildMarker(res[i]);
}

方案2:用ES6的let声明循环变量(简洁现代)

如果你的项目支持ES6,直接把循环里的var i改成let i就行——let会生成块级作用域,每次循环都会创建一个独立的i变量,事件函数会引用当前循环的i:

for (let i = 0; i < res.length; i++) {
  const marker = new google.maps.Marker({
    position: new google.maps.LatLng(res[i].position.lat, res[i].position.long),
    title: '',
    orderid: res[i].id,
    map: map,
    icon: icon,
  });

  google.maps.event.addListener(marker, "click", function() {
    const infoContent = `
      <div class="info-window">
        <h4>${res[i].name}</h4>
        <p>订单ID:${res[i].id}</p>
        <p>日期:${res[i].date}</p>
      </div>
    `;
    const infoWindow = new google.maps.InfoWindow({ content: infoContent });
    infoWindow.open(map, marker);
  });
}

额外优化建议

如果页面上marker很多,建议复用同一个InfoWindow,而不是每次点击都新建,这样性能会更好:

// 全局只创建一个InfoWindow实例
const globalInfoWindow = new google.maps.InfoWindow();

function buildMarker(item) {
  const marker = new google.maps.Marker({
    position: new google.maps.LatLng(item.position.lat, item.position.long),
    title: '',
    orderid: item.id,
    map: map,
    icon: icon,
  });

  google.maps.event.addListener(marker, "click", function() {
    const infoContent = `
      <div class="info-window">
        <h4>${item.name}</h4>
        <p>订单ID:${item.id}</p>
        <p>日期:${item.date}</p>
      </div>
    `;
    globalInfoWindow.setContent(infoContent);
    globalInfoWindow.open(map, marker);
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:31:47