React循环渲染Google Maps Marker与InfoWindow时括号不匹配报错
Google Maps API 独立InfoWindow 括号错误修复
问题根源
循环绑定Marker点击事件时,若未处理作用域问题,不仅会导致所有Marker共用同一个InfoWindow,还容易因闭包写法失误出现括号不匹配。
正确实现代码
方式1:用forEach循环(自带作用域,无需额外闭包)
// 示例位置数组 const locations = [ { lat: 39.9042, lng: 116.4074, info: '<h3>北京</h3><p>中国首都</p>' }, { lat: 31.2304, lng: 121.4737, info: '<h3>上海</h3><p>经济中心</p>' } ]; // 初始化地图 const map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: { lat: 35.8617, lng: 104.1954 } }); // 遍历创建Marker和独立InfoWindow locations.forEach(item => { // 创建当前Marker专属的InfoWindow const infoWindow = new google.maps.InfoWindow({ content: item.info }); // 创建Marker const marker = new google.maps.Marker({ position: { lat: item.lat, lng: item.lng }, map: map }); // 绑定点击事件,打开对应InfoWindow marker.addListener('click', () => { infoWindow.open(map, marker); }); });
方式2:用for循环(需自执行函数创建作用域,注意括号)
for (let i = 0; i < locations.length; i++) { // 自执行函数包裹,传递当前索引,避免作用域污染和括号错误 (function(index) { const item = locations[index]; const infoWindow = new google.maps.InfoWindow({ content: item.info }); const marker = new google.maps.Marker({ position: { lat: item.lat, lng: item.lng }, map: map }); marker.addListener('click', function() { infoWindow.open(map, marker); }); })(i); // 此处括号必须保留,否则会出现括号不匹配语法错误 }
括号错误排查技巧
- 自执行函数必须写成
(function(){...})(),末尾的执行括号不能省略 - 箭头函数回调:单行逻辑可省略大括号,多行逻辑必须添加,别混用导致括号嵌套混乱
- 若InfoWindow的content是HTML字符串,检查标签是否闭合,避免HTML括号干扰JS语法
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

