Javascript仅显示最后一个标记

时间:2012-11-29 19:35:48

标签: javascript function variables closures anonymous

以下代码从/home.json URL中获取一些JSON数据,其中包含6个用户的5个微博。但是,仅显示最后4个标记(甚至不是第5个!!)。我花了2天的时间来找到这个bug,但遗憾的是我无法理解为什么这不起作用。如果有人能帮助我,我会非常感激!

我已通过警告测试了所有lon / Lat变量!他们都有适当的数据。地图应该没问题,因为显示了最后4个!!最可能的问题在于我的闭包定义,但我真的无法理解我做错了什么..

var GMAPS = window.GMAPS || {};
GMAPS.mainMap = function() {
  var map;
  var infowindow = new google.maps.InfoWindow();
  var jsonObject = {};

  function addMarkers() {
    var xhr = new XMLHttpRequest();
    xhr.open( "GET", "/home.json", true );
    xhr.onreadystatechange = function () {
      if ( xhr.readyState == 4 && xhr.status == 200 ) {
        jsonObject = JSON.parse( xhr.responseText );
        for (var i=0; i<jsonObject.length; i++) {
          for (var j=0; j<jsonObject[i].microposts.length; j++) {
            (function(Name, Title, Content, Latitude, Longitude) {
              return function() {
                //alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n");  //<-- this works!
                var position = new google.maps.LatLng(Latitude, Longitude);
                var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
                                + "<br />" + Content;

                var marker = new google.maps.Marker({
                  position: position,
                  title: Title,
                  map: map
                });
                google.maps.event.addListener(marker, 'click', (function(marker, contentString) { 
                    return function() { 
                      infowindow.setContent(contentString); 
                      infowindow.open(map, marker); 
                    } 
                })(marker, contentString));
              };
            })(jsonObject[i].name, jsonObject[i].microposts[j].title,
               jsonObject[i].microposts[j].content,
               jsonObject[i].microposts[j].lat,
               jsonObject[i].microposts[j].lon)();
          }
        }
      }
    };
    xhr.send(null);
  }

  function createMap() {
    map = new google.maps.Map(document.getElementById('main_map'), {
      zoom: 10,
      panControl: true,
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
      },
      mapTypeControl: true,
      scaleControl: true,
      streetViewControl: true,
      overviewMapControl: true,
      scrollwheel: false,
      center: new google.maps.LatLng(37.975327,23.728701),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  }


  function initAddress() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    }
    else {
      var position = new google.maps.LatLng(0, 0);
      map.setCenter(position);
    }
  }

  function showPosition(position) {
    var position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    map.setCenter(position);
  }

  return {

    initMap : function() {
      createMap();
      initAddress();
      addMarkers();
    }
  };
}();

document.addEventListener("DOMContentLoaded", GMAPS.mainMap.initMap, false);

2 个答案:

答案 0 :(得分:1)

**注意:在IIFE结尾处你有一套不必要的额外的parens。

在IIFE之前(在最里面的for循环中),尝试添加:

var jObj = jsonObject[i], mPost = jObj.microposts[j];

然后用以下代码替换IIFE的参数:

(function(Name, Title, Content, Latitude, Longitude) {
              return function() {
                //alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n");  //<-- this works!
                var position = new google.maps.LatLng(Latitude, Longitude);
                var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
                                + "<br />" + Content;

                var marker = new google.maps.Marker({
                  position: position,
                  title: Title,
                  map: map
                });
                google.maps.event.addListener(marker, 'click', (function(marker, contentString) { 
                    return function() { 
                      infowindow.setContent(contentString); 
                      infowindow.open(map, marker); 
                    } 
                })(marker, contentString));
              };
            })(jObj.name, mPost.title, mPost.content, mPost.lat, mPost.lon);

答案 1 :(得分:0)

以下代码应该有效。我仍然不明白为什么你有额外的括号。

xhr.onreadystatechange = function() {
  var i = 0, j = 0;
  if ( xhr.readyState == 4 && xhr.status == 200 ) {
    jsonObject = JSON.parse( xhr.responseText );
    for (var ilen = jsonObject.length; i < ilen;) {
      for (var jObj = jsonObject[i++], jlen = jObj.microposts.length; j < jlen;) {
        var mPost = jObj.microposts[j++];
        (function(Name, Title, Content, Latitude, Longitude) {
          return function() {
            //alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n");  //<-- this works!
            var position = new google.maps.LatLng(Latitude, Longitude);
            var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
                            + "<br />" + Content;

            var marker = new google.maps.Marker({
              position: position,
              title: Title,
              map: map
            });
            google.maps.event.addListener(marker, 'click', (function(marker, contentString) { 
                return function() { 
                  infowindow.setContent(contentString); 
                  infowindow.open(map, marker); 
                } 
            })(marker, contentString));
          };
        })(
          jObj.name, mPost.title, mPost.content, mPost.lat, mPost.lon
        );
      }
    }
  }
};