2010-11-01 95 views
5

我有一個地圖與多條折線,並希望打開線特定infowindow單擊該行時。多條折線和infowindows與谷歌地圖V3

到目前爲止我的代碼只顯示最後一次迭代的內容。

我發現了兩個非常好的例子,我想要什麼,但經過幾個小時的嘗試,我仍然沒有更進一步。
例1:http://srsz750.appspot.com/api3/polylines-multiple.html
例2:http://www.geocodezip.com/v3_GenericMapBrowser.asp?filename=flights090414.xml

所以,你是我的最後一槍:-S

這裏是我的代碼,只顯示最後一次迭代的內容:

for (var i = 0; i < locations.length; i++) { 
var route = locations[i]; // locations is an array of route-arrays. 
//route is an array with details. route[0] contains the description. 

var imageStart = 'img/rijder.png'; 
var polyOptions = { 
    strokeColor: '#0000FF', 
     strokeOpacity: 1.0, 
    strokeWeight: 3 
    }  

    poly = new google.maps.Polyline(polyOptions, info); 
    var path = poly.getPath(); 

//line text 

var info = route[0]; 
google.maps.event.addListener(poly, 'click', function(event) { 
    infowindow.setContent(info); 
    infowindow.position = event.latLng; 
infowindow.open(map); 
    }); 

//startmarker 
var startLatLng = new google.maps.LatLng(route[1], route[2]); 
var smarker = new google.maps.Marker({ 
    position: startLatLng, 
    map: map, 
    icon: imageStart, 
    title: route[7], 
    html: route[0]  
}); 
path.push(startLatLng); 
//starttext 

google.maps.event.addListener(smarker, "click", function() { 
     infowindow.setContent(this.html); 
     infowindow.open(map, this); 
     }); 

//endmarker 
var endLatLng = new google.maps.LatLng(route[4], route[5]); 
var emarker = new google.maps.Marker({ 
    position: endLatLng, 
    map: map, 
    icon: imageEnd, 
    title: route[8], 
    html: route[3]  
}); 
path.push(endLatLng); 
//endtext 

google.maps.event.addListener(emarker, "click", function() { 
      infowindow.setContent(this.html); 
      infowindow.open(map, this); 
     }); 
//close line and put on the map 
poly.setMap(map); 
} 
} 

這裏是我期望能夠工作的代碼,但是所有行都消失了(只有相關代碼,我還添加了一個鼠標懸停功能):

//line text 
    google.maps.event.addListener(poly, 'click', (function(event,index){ 
    return function(){ 
    var routeinfw = locations[index]; 
    var inf = routeinfw[0]; 
    infowindow.setContent(inf); 
    infowindow.position = mouselocation; 
    infowindow.open(map); 
     }; 
    })(event,i)); 

//starticon 

回答

9

就像在您發佈的例子,創建一個函數來創建click事件偵聽器,然後從該位置循環內部稱之爲:

function createInfoWindow(poly,content) { 
    google.maps.event.addListener(poly, 'click', function(event) { 
     infowindow.content = content; 
     infowindow.position = event.latLng; 
     infowindow.open(map); 
    }); 
} 

而且你可以在循環結束稱之爲:

createInfoWindow(poly,info); 
+1

你的代碼解決了多邊形的一個錨點問題(它們不能很好地與event.latLng - 標記結合,確定)。因此,明確地定位infowindow,而不是'infowindow.open(map,event.latLng)',這對Google地圖的多邊形事件界面來說是一個很好的解決方法。 – 2012-02-27 13:09:31

+1

很高興幫助! – ifaour 2012-02-27 15:02:58

相關問題