变量在forEach循环中被覆盖

时间:2016-03-16 13:37:07

标签: javascript google-maps

我的所有Google地图标记都使用相同的 infoText 。 知道为什么infowindow.setContent('hi' + i)有效而不是infowindow.setContent(infoText)? 使用infoText变量作为内容时,我的所有20个标记都会获得相同的内容。 (停车场20号)

编辑:将代码更新为工作示例。

 49     for (i = 0; i < locations.length; i++) {
 50       if (locations[i]['available'] === true) {
 51         icon = 'http://www.google.com/mapfiles/ms/micons/green.png';
 52         text = 'Available Parking nr ' + i;
 53         generateInfoBox(text, icon)
 54       } else {
 55         icon = small_red_circle;
 56         text = 'Parking nr ' + i;
 57         generateInfoBox(text, icon)
 58       }
 59
 60       function generateInfoBox(text, icon) {
 61         marker = new google.maps.Marker({
 62           position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
 63           map: map,
 64           icon: icon
 65         });
 66
 67         google.maps.event.addListener(marker, 'click', (function(marker, i) {
 68           return function() {
 69             infowindow.setContent(text);
 70             infowindow.open(map, marker);
 71           }
 72         })(marker, i));
 73       }

2 个答案:

答案 0 :(得分:1)

infoText是全局的,当事件执行时,它的最后一个值已更改。另一方面,i是函数上下文中的局部变量,因此它始终不同。

无论如何你切片,代码

 for (i = 0; i < locations.length; i++) {
      if (locations[i]['available'] === true) {
                icon = 'http://www.google.com/mapfiles/ms/micons/green.png';
                infoText = 'Parking nr ' + i;
            } else {
                infoText = 'Parking nr ' + i;
            }

除了将infoText设置为&#39; Parking nr 20&#39;

之外别无其他

这是一个一般的例子:

for (var i=0; i<20; i++) {
  setTimeout(function() { console.log(i); },100);
}

将输出20次&#39; 20&#39;

for (var i=0; i<20; i++) {
  (function() {
    var j=i;
    setTimeout(function() { console.log(j); },100);
  })();
}

将输出0到19.Javascript只有函数范围,这就是为什么每个j都不同,但是i是上述范围中的那个。

答案 1 :(得分:0)

您需要infoText以及markeri上的功能结束:

google.maps.event.addListener(marker, 'click', (function(marker, i, infoText) {
  console.log("infoText from withing addListener: ", infoText);
  //  ^ Works
  return function() {
    infowindow.setContent('hi ' + i+"<br>"+infoText);   // This works. E.g 'hi1', 'hi2', etc
    //infowindow.setContent(infoText); // Every infowindow gets 'Parking nr 20' if I use this.
    infowindow.open(map, marker);
  }
})(marker, i, infoText));

proof of concept fiddle

代码段

&#13;
&#13;
var geocoder;
var map;

function initialize() {
  drawMap(locations);
}
google.maps.event.addDomListener(window, "load", initialize);

function drawMap(locations) {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: {
      lat: 40.735657,
      lng: -74.1723667
    }
  });

  var marker, i, icon, infoText;
  var infowindow = new google.maps.InfoWindow();

  for (i = 0; i < locations.length; i++) {
    if (locations[i]['available'] === true) {
      icon = 'http://www.google.com/mapfiles/ms/micons/green.png';
      infoText = 'Available Parking nr ' + i;
    } else {
      icon = 'http://www.google.com/mapfiles/ms/micons/blue.png';
      infoText = 'Parking nr ' + i;
    }

    // Create a marker
    console.log("Will use the infotext: ", infoText);
    // ^^ Displays correct text
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
      map: map,
      icon: icon
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i, infoText) {
      console.log("infoText from withing addListener: ", infoText);
      //  ^ Works
      return function() {
        infowindow.setContent('hi ' + i + "<br>" + infoText); // This works. E.g 'hi1', 'hi2', etc
        infowindow.open(map, marker);
      }
    })(marker, i, infoText));

  }
}
var locations = [{
  addr: "New York, NY, USA",
  lat: 40.7127837,
  lng: -74.0059413,
  available: false
}, {
  addr: "Newark, NJ, USA",
  lat: 40.735657,
  lng: -74.1723667,
  available: true
}, ]
&#13;
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;
&#13;
&#13;