我有一个小问题,我有以下代码,除了标记的标题外,其他所有功能都正常运行。它始终显示数组列表的最后一个标题。有人知道为什么会出现此错误吗?

码:

$(document).ready(function() {

            var options = {
                zoom: 7,
                center: new google.maps.LatLng(42.19708, 2.19075),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControl: true
            };

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

            var companys = [
                ['Giga S.L', 'Plaça de Catalunya, Barcelona'],
                ['Torre M', 'Plaça d\'Espanya, Barcelona']
            ];

            var address;
            var title;

            for (var i = 0; i < companys.length; i++) {
                address = companys[i][1];
                title = companys[i][0];

                geocoder.geocode({'address': address}, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);

                        new google.maps.Marker({
                            map: map,
                            animation: google.maps.Animation.DROP,
                            position: results[0].geometry.location,
                            title: title // ERROR: ALWAYS THE SAME TITLE
                        });
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }
        });


先感谢您。

最好的祝福。

最佳答案

解决此问题的一种方法是将对geocode的调用包装在immediately-invoked function expression(IFFE)中,将变量作为参数传递:

(function(address, title) { // the variables are passed in here as function parameters

  geocoder.geocode({'address': address}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);

      new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        position: results[0].geometry.location,
        title: title
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

}(address, title)); // pass in address/title into the IFFE

10-07 19:24