变量在子函数中变为未定义

时间:2013-06-16 07:30:24

标签: javascript google-maps

我使用谷歌地图javascript api来显示一个充满地点标记的地图。标记显示但是一旦在控制台上单击它们就会出现错误:“未捕获的TypeError:无法在infowindow.setContent('<div><p>'+locations[i][0]+'</p></div>');读取未定义的属性'0'。我发现问题是脚本不知道i是什么。我已经通过用i代替数字来测试这个结论,它可以正常工作。到目前为止,我已尝试将i作为全局变量并将其值测试为window.i。它仍然没有用,但在控制台中它显示了它的最后一次计数。有什么我做错了吗?

function initialize() {
    var locations = [<?php echo $jscript; ?>];

    map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 8,
        center: new google.maps.LatLng(32.639594, -97.117879),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

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

    var marker = '';
    var i = 0;
    for (i = 0; i < locations.length; i++) {
        var geocoder_map = new google.maps.Geocoder();
        var addlocat;

        geocoder_map.geocode({'address': locations[i][0]}, function (results, status) {
            if (results) {
                addlocat = results[0].geometry.location;

                marker = new google.maps.Marker({
                    position: addlocat,
                    map: map
                });

                google.maps.event.addListener(marker, 'click', (function (marker, i) {
                    return function () {
                        infowindow.setContent('<div><p>' + locations[i][0] + '</p></div>');
                        infowindow.open(map, marker);
                    }
                })(marker, i));

            }
        });
    }
}

google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:0)

遵循@FelixKling的结构我把它弄掉了,它首先尝试了:

<script>
function initialize() {
      locations = [<?php echo $jscript; ?>];

    map = new google.maps.Map(document.getElementById('map-canvas'), {
      zoom: 8,
      center: new google.maps.LatLng(32.639594, -97.117879),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    infowindow = new google.maps.InfoWindow();

    var i = 0;
    for (i = 0; i < locations.length; i++) {  
    geocode(i, locations[i])
   }
}

function geocode(i, location){
    var geocoder_map = new google.maps.Geocoder();
    var addlocat;

    geocoder_map.geocode( { 'address': location[0]}, function(results, status) {
            if(results){
            addlocat = results[0].geometry.location; 

      var marker = new google.maps.Marker({
        position: addlocat,
        map: map
      });

      google.maps.event.addListener(marker, 'click',
        return function() {
          infowindow.setContent('<div><p>'+location[0]+'</p></div>');
          infowindow.open(map, marker);
        });
      }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>