从数组中设置地图标记标题

时间:2013-03-18 09:30:26

标签: sencha-touch sencha-touch-2 google-maps-markers

我正在尝试使用地理编码从数组创建地图标记。我将地址存储在数组中以及地址的标题。问题出在我的循环中,标题被设置为我最后一个数组的最后一个值,尽管从数组中的地址正确设置了标记。这是我的代码:

maprender : function (comp, map) {
  new google.maps.Marker({
    animation: google.maps.Animation.DROP,
    position: new google.maps.LatLng(this._geo.getLatitude(), this._geo.getLongitude()),
    map: map
  });

  var names = new Array("ABC","DEF","GHI"),
      mapAdd = new Array();

  mapAdd[0] = "Address 1";
  mapAdd[1] = "Address 2";
  mapAdd[2] = "Address 3";

  var geocoder = new google.maps.Geocoder(); 

  for (var i = 0; i < mapAdd.length; i++) {
    var lat = 0,
        lng = 0,
        x = names[i];

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

          console.log(lat + " " + lng);
          new google.maps.Marker({
            position: new google.maps.LatLng(lat, lng),
            title: x,
            map: map
          });
          console.log(x);
        }
      }
    });

  }

}

标题在所有标记上返回“GHI”。

1 个答案:

答案 0 :(得分:0)

基于http://blog.jbrantly.com/2010/04/creating-javascript-function-inside.html

以这种方式试试

function geocode(i) {

  var lat = 0,
      lng = 0,
      x = names[i];

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

        console.log(lat + " " + lng);
        new google.maps.Marker({
          position: new google.maps.LatLng(lat, lng),
          title: x,
          map: map
        });
        console.log(x);
      }
    }
  });

}

for (var i = 0; i < mapAdd.length; i++) {
  geocode(i);
}

希望这有帮助

相关问题