2012-04-19 92 views
2

我有多個標記。在按鈕上打開信息框點擊「外部」地圖(谷歌地圖v3)

我使用該代碼的每一標誌點擊後能夠成功地OPENINFO箱(是其設置標記的環內)

for (var i = 0; i < markers.length; i++) { 
.... 
.... 
.... 
google.maps.event.addListener(marker, "click", function() { 
      //alert(this.html); 
      infowindow.setContent(this.html); 
      infowindow.open(map, this); 
     }); 
} 

上面的代碼工作得很好。

但是現在我想讓每個標記的信息框在地圖上點擊的按鈕上打開。我在同一個循環中嘗試了一些東西。

for (var i = 0; i < markers.length; i++) { 
.... 
.... 
.... 
var chandu = document.getElementById(i); 
     google.maps.event.addDomListener(chandu, "click", function(){ 
      infowindow.setContent(this.html); 
      infowindow.open(map, this); 
      //alert("Yo"); 
     }); 
} 

和我有HTML按鈕點擊這樣

<a href="#" id="0">0</a> 
    <a href="#" id="1">1</a> 
    <a href="#" id="2">2</a> 
    <a href="#" id="3">3</a> 
    <a href="#" id="4">4</a> 
    <a href="#" id="5">5</a> 

但這點擊HTML鏈接部分的不woork

回答

4

工作的解決方案我現在看起來像這樣

var chandu = document.getElementById(i); 
chandu.onclick = generateTriggerCallback(marker,"click"); 

而且還有一個功能出來的for循環

function generateTriggerCallback(object, eventType) { 
      return function() { 
       google.maps.event.trigger(object, eventType); 
      }; 
     } 

貸:我想出了這個答案尋找到後此示例的源代碼http://gmaps-samples-v3.googlecode.com/svn/trunk/sidebar/random-markers.html

+0

+1正是我需要的。 ;-) – 2013-11-07 16:54:14

1

的問題是,你打算重用的「本」在你的代碼來處理的超級鏈接點擊:

var chandu = document.getElementById(i); 
     google.maps.event.addDomListener(chandu, "click", function(){ 
      infowindow.setContent(this.html); 
      infowindow.open(map, this); 
      //alert("Yo"); 
     }); 
} 

第一「這」是正確的 - this.html是的HTML超鏈接(不是標記)。 infowindow.open(map,this)中的第二個'this'不正確。在你的工作代碼中,這引用了標記。在您的非工作代碼中,這引用了超鏈接。這個對象在兩行之間不會改變。而不是infowindow.open(map,this),你需要infowindow.open(map,this.id),因爲你的a標籤的id值與標記數組中的索引相同。

請注意,這是錯誤的HTML,因爲id屬性不能以數字開頭,所以它必須以字母開頭。如果你試圖驗證你的HTMl,它不會。你需要在ID值上加一個字母前綴,也許是'm'。然後,當你需要採用id值的子字符串時,剝離你所擁有的'm'。

+0

是的,經過很多console.log,昨天我意識到我在用「this」所犯的錯誤。並感謝有關id屬性的信息(儘管現在它可以在id中首先開始的數字)。我將該解決方案作爲答案發布。 – cjmling 2012-04-20 04:02:48

相關問題