多次读取数组会产生错误javascript

时间:2012-11-25 13:21:18

标签: javascript arrays google-maps

我正在尝试使用一些标记创建一个需要谷歌地图的网站 我有一个问题,多次读取一个javascript 2D数组,它给我错误

  

无法读取未定义的属性“0”

这里是我的代码

function initialize() {
          var locations = [
          //'City',LatLng,LatLng,Zoom
          ['Egypt', 26.820553, 30.802498, 6], //Center of whole map
          ['Alexandria', 'Egypt'], //pointer
          ['Mansoura', 'Egypt'], //pointer
          ['Assiut', 'Egypt'] //pointer
          ];

          var mapOptions = {
              zoom: locations[0][3],
              center: new google.maps.LatLng(locations[0][1], locations[0][2]),
              mapTypeId: google.maps.MapTypeId.ROADMAP
          };

          var map = new google.maps.Map(document.getElementById('map_canvas'),
          mapOptions);

          var infowindow = new google.maps.InfoWindow();

          var marker, i;
          var geocoder = new google.maps.Geocoder();
          var image = 'flag.png';

          for (i = 1; i < locations.length; i++) {
              geocoder.geocode({ 'address': locations[i][0] + ' ' + locations[i][1] }, function (results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {

                      marker = new google.maps.Marker({
                          animation: google.maps.Animation.DROP,
                          map: map,
                          icon: image,
                          position: results[0].geometry.location,
                          title: locations[i][0]
                      });

                      google.maps.event.addListener(marker, 'click', (function (marker, i) {
                          return function () {
                              infowindow.setContent('<b style="font-size:30px;">' + locations[i][0] + '</b>'
                                  + '<br><b>Starting Date:</b> 11/5/2012'
                                  + '<br><b>Ending Date:</b> 30/5/2012'
                                  + '<br><a href="google.com">Event Website</a>');
                              infowindow.open(map, marker);
                          }
                      })(marker, i));
                  }
              });
          }
      }

      function loadScript() {
          var script = document.createElement('script');
          script.type = 'text/javascript';
          script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyA6yYH66F1L3NgHAobufuUF6l-jjVCLwfE&sensor=false&' +
          'callback=initialize';
          document.body.appendChild(script);
      }

      window.onload = loadScript;

我在本节中遇到了错误 当我试图多次阅读[i] [0]的位置时。

for (i = 1; i < locations.length; i++) {
              geocoder.geocode({ 'address': locations[i][0] + ' ' + locations[i][1] }, function (results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {

                      marker = new google.maps.Marker({
                          animation: google.maps.Animation.DROP,
                          map: map,
                          icon: image,
                          position: results[0].geometry.location,
                          title: locations[i][0]
                      });

                      google.maps.event.addListener(marker, 'click', (function (marker, i) {
                          return function () {
                              infowindow.setContent('<b style="font-size:30px;">' + locations[i][0] + '</b>'
                                  + '<br><b>Starting Date:</b> 11/5/2012'
                                  + '<br><b>Ending Date:</b> 30/5/2012'
                                  + '<br><a href="google.com">Event Website</a>');
                              infowindow.open(map, marker);
                          }
                      })(marker, i));
                  }
              });
          }

如果无论如何我都可以在c#代码中处理这段代码,那就很好了

1 个答案:

答案 0 :(得分:3)

[忽略之前关于results的评论

问题是您在geocode()回调中引用了i。 geocode()方法是异步的 - 即在for循环已经完成后,你的回调被称为。那时,i = 4,意味着locations [i]未定义。

如果没有意义,你应该读一下闭包是如何工作的,但基本上解决方法是将你的for循环中的代码放到一个单独的函数中并将它传递给你想要使用的位置条目,比如这样:

function geocodeLocation(location) {
  geocoder.geocode({ 'address': location[0] + ' ' + location[1] },
    function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        marker = new google.maps.Marker({
          animation: google.maps.Animation.DROP,
          map: map,
          icon: image,
          position: results[0].geometry.location,
          title: location[0]
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
          return function () {
            infowindow.setContent('<b style="font-size:30px;">' + location[0] + '</b>'
              + '<br><b>Starting Date:</b> 11/5/2012'
              + '<br><b>Ending Date:</b> 30/5/2012'
              + '<br><a href="google.com">Event Website</a>');
            infowindow.open(map, marker);
          }
        })(marker, i));
      }
    }
  );
}


for (var i = 1; i < locations.length; i++) {
  geocodeLocation(locations[i]);
}