1

location[i][0]からの値を表示するための情報ウィンドウを取得するためのヘルプが必要です

location [i] [1]はアドレス値に対しては問題なく機能していますが、var"locations"から情報ウィンドウ内のすべてのマーカーにカスタムタイトルを設定できるようにしたいと思います。

varを定義して、コンテンツと情報ウィンドウがそのように機能するように設定できますが、すべてのマーカーで同じであり、varの「場所」から取得することはありません。

どんな助けでも大歓迎です!

function initialize() {


geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(
document.getElementById("map_canvas"),
myOptions);
setMarkers(map, locations);
}

var locations = [
['Bondi Beach', '798 9th Ave, New York, NY', 4],
['Coogee Beach', '42 E 29th St, New York, NY', 5],
['Cronulla Beach', '56 W 25th St, New York, NY', 3],

];



function setMarkers(map, locations) {

var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
 var marker, i; 

for (var i=0; i<=locations.length; i++) { 


   geocoder.geocode({'address': locations[i][1]}, function(results, status) { 

    marker = new google.maps.Marker({
    position: results[0].geometry.location,
    map: map,


    });


  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {

      infowindow.open(map, marker);
      infowindow.setContent(locations[i][0]);
    }
  })(marker, i));

bounds.extend(marker.getPosition());


map.fitBounds(bounds);

})
  }
}
4

1 に答える 1

1

何が起こっているのかというと、クリックイベントリスナーがi = 3(ループが終了した後のiの最後の値)を取得しているため、この未定義のステータスのためにインフォウィンドウは表示されません。

ジオコーダーが導入されたためfor、クリックリスナーが機能を割り当てる前に、外側のループが終了します。したがって、リスナーでiの正しい値を維持するには、ジオコーディングの外部にある別の関数スコープラッパーが必要です。

function setMarkers(map, locations) {

  var infowindow = new google.maps.InfoWindow();
  var bounds = new google.maps.LatLngBounds();
  var marker, i; 

  //CHANGED REMOVED EQUALS SIGN
  for (var i=0; i<locations.length; i++) { 

   //ADDED
   (function(i) {
   geocoder.geocode({'address': locations[i][1]}, function(results, status) { 

     marker = new google.maps.Marker({
       position: results[0].geometry.location,

      //REMOVED COMMA
       map: map
     });

     google.maps.event.addListener(marker, 'click', (function(marker, i) {
       return function() {

         //CHANGED ORDER
         infowindow.setContent(locations[i][0]);
         infowindow.open(map, marker);
       }
     })(marker, i));

     bounds.extend(marker.getPosition());
     map.fitBounds(bounds);
     });

    // ADDED
    })(i);
   }
 }
于 2012-06-06T22:48:23.950 に答える