2012-07-13 50 views
20

我有這個代碼,我顯示和設置我所有的標記。如何添加帶有此代碼的標記信息的彈出窗口?我在文本上添加了「i」變量,但它在所有標記彈出的「test-723」上設置,其中723是「i」變量的最後一個值。哪裏不對?如何使用Google Maps API在標記上設置彈出窗口?

for (var i = 0; i < arraylng.length-1; i++) { 
    var marker = new google.maps.Marker({ 
    position: new google.maps.LatLng(arraylng[i], arraylat[i]) 
    }); 
    var infowindow = new google.maps.InfoWindow({ 
    content: " " 
    }); 
    google.maps.event.addListener(marker, 'click', function() { 
    infowindow.setContent('test: ' + i + ''); 
    infowindow.open(map, this); 
    }); 
    markers.push(marker); 
} 

回答

38

首先,將環路條件更改爲i < arraylng.length。現在它不捕獲數組的最後一個元素。

JavaScript變量與函數作用域一起工作,因此您需要爲每個標記偵聽器調用一個函數來創建正確的變量引用。您可以使用匿名函數,as seen here,或定義一個函數用於創建點擊收聽:

多個信息窗口:

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

最有可能你不會想不止一個信息窗口同時打開,因爲點擊關閉x是令人討厭的。然後,你將只需要一個信息窗口對象,並設置爲標記被點擊的內容:

單信息窗口:內環路

... 
    var infowindow = new google.maps.InfoWindow(); 

    for (var i = 0; i < arraylng.length-1; i++) { 
    var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(arraylng[i], arraylat[i]), 
     map: map 
    }); 

    makeInfoWindowEvent(map, infowindow, "test" + i, marker); 

    markers.push(marker); 
    } 
} 

function makeInfoWindowEvent(map, infowindow, contentString, marker) { 
    google.maps.event.addListener(marker, 'click', function() { 
    infowindow.setContent(contentString); 
    infowindow.open(map, marker); 
    }); 
} 
+1

的解決方案,非常好,謝謝! – whoah 2012-07-15 09:50:44

+8

您的jsfiddle鏈接已過期。 – 2015-07-21 14:45:26

+0

鏈接不工作... -1 – 2016-08-12 13:40:45

0

這是因爲變量i在循環不使用,但點擊標記時 - 然後我等於最後一個索引+ 1 ... addListener是異步的,不同步的。

刪除infowindow.setContent('test: ' + i + '');並用content: 'test: ' + i替換content: " "。這應該可以解決你的問題。

+0

http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/做了很好的解釋 – 2016-05-24 15:24:10

1
var marker = new google.maps.Marker({ 
       position: myLatLng, 
       .... 
       content: point[4] 
      }); 
google.maps.event.addListener(marker, 'click', function() { 
      infowindow.setContent(this.content); 
      infowindow.open(map, this); 
      }); 

代碼。這對我完美的工作。

相關問題