如何在foreach循环中为每个map元素动态分配对应坐标值
解决方案
Array.prototype.forEach的回调函数支持第二个入参,代表当前遍历元素的索引值,直接用这个索引读取coordinates数组的对应项即可,修改后的代码如下:
function initMap() { const coordinates = [ { "lat": 123, "lng": 123 }, { "lat": 123, "lng": 123 }, { "lat": 123, "lng": 123 } ] const mapElements = document.querySelectorAll('.map'); // 给回调函数加第二个参数index,代表当前遍历的下标 mapElements.forEach((element, index) => { // 可选:加上边界判断避免坐标数组长度不足时数组越界报错 if (index >= coordinates.length) return // coordinates数组项本身就是lat+lng结构,可直接使用无需重新构造 const uluru = coordinates[index]; console.log(uluru); const map = new google.maps.Map(element, { zoom: 4, center: uluru, }); const marker = new google.maps.Marker({ position: uluru, map: map, }); }); }
注意事项
- 要保证
.map元素和坐标项的顺序对应,即可实现第一个地图用第一个坐标、第二个地图用第二个坐标的需求 - 如果页面中
.map元素的数量多于coordinates数组的长度,超出部分的地图不会被初始化,可根据实际需求调整边界判断逻辑
内容的提问来源于stack exchange,提问作者Meana
相关产品推荐
相关产品推荐

