2013-04-09 168 views
2

我想用不同的值創建三個標記。在for循環內我具備以下條件:如何在Google Maps v3中爲每個標記創建infowindow?

var marker = new google.maps.Marker({map: map, position: point, clickable: true}); 

marker.info = new google.maps.InfoWindow({ 
    content: '<b>Speed:</b> ' + values.inst + ' knots' 
}); 

google.maps.event.addListener(marker, 'click', function() { 
    marker.info.open(map, marker); 
}); 

我遇到的問題是,當我點擊任何3個標誌,只爲最後的標記信息窗口創建彈起。我如何解決這個問題?

回答

0

您需要將此代碼移出for循環,並轉入您從for循環中調用的單獨函數。如果你發佈了更多的代碼,包括循環和數組循環迭代,我可以給出更具體的建議。

但是作爲一個例子:

var places = [ 
    { lat:1, lng:1, name:'one one' } 
    { lat:-1, lng:-1, name:'minus one one' } 
]; 

for(var i = 0, n = places.length; i < n; i++) { 
    addPlace(places[i]); 
} 

function addPlace(place) { 
    // here you have place.lat, place.lng, and place.name to work with 
} 
3

也許你會找到有用下面的例子:

var cityList = [ 
      ['Chicago', 41.850033, -87.6500523, 1], 
      ['Illinois', 40.797177,-89.406738, 2] 
     ] 

function addMarkers() 
{ 
    var marker, 
    i, 
    infowindow = new google.maps.InfoWindow(); 

    for (i = 0; i < cityList.length; i++) 
    { 
     marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(cityList[i][1], cityList[i][2]), 
      map: map, 
      title: cityList[i][0] 
     }); 

     google.maps.event.addListener(marker, 'click', (function(marker, i) { 
      return function() { 
       infowindow.setContent(cityList[i][0]); 
       infowindow.open(map, marker); 
      } 
     })(marker, i)); 
    } 
} 
相關問題