0

我使用 Google Maps javascript api 来显示一张充满位置标记的地图。标记会显示,但一旦在控制台上单击它们就会出现错误:“Uncaught TypeError: Cannot read property '0' of undefined” at infowindow.setContent('<div><p>'+locations[i][0]+'</p></div>');。我发现问题是脚本不知道是什么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);
4

1 回答 1

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>
于 2013-06-16T08:13:58.537 回答