2016-12-03 45 views
0

我試圖把一個infowindow與不同的內容使用for(),但它不起作用。這是我的代碼:谷歌地圖infowindows問題與()

var infowindow=[]; 
var myMarker=[]; 
var marker=[]; 
for (i = 0; i < dl.length; i++) { 
    myMarker[i]=new google.maps.LatLng(lt[i], ln[i]); 
    marker[i] = new google.maps.Marker({ 
    position: myMarker[i], 
    map: map 
    }); 
} 

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



google.maps.event.addListener(marker[i],'mouseover', function(){ 

    infowindow[i] = new google.maps.InfoWindow({ 
    content:dl[i] 
    }); 
    infowindow[i].open(map,marker[i]); 
    }); 

    google.maps.event.addListener(marker[i],'mouseout',function() { 
    infowindow[i].close(); 
    }); 
    google.maps.event.addListener(marker[i],'click',function() { 
    alert("Y ahora te abriría otra pagina... si tuviera una"+i); 
    }); 


} 

一切都很酷的第一次,但是當我試圖使用事件監聽器變壞。

變量:dl[]lt[],ln[]之前被初始化。

回答

0

infowindow不能像那樣工作。創建infowindow的單個副本(而不是維護數組),並在每個標記的mouseover事件期間使用infowindow.setContent()設置其內容。

編輯:你在你的迴應解決方案將工作,或者在這裏是一個更簡潔的解決方案:

var myMarker=[]; 
var marker; 
var infoWindow = new google.maps.InfoWindow(); 
for (i = 0; i < dl.length; i++) { 
    myMarker[i]=new google.maps.LatLng(lt[i], ln[i]); 
    marker = new google.maps.Marker({ 
    position: myMarker[i], 
    map: map 
    }); 
    (function(msg) {marker.addListener('mouseover', function() { 
    infoWindow.setContent(msg); 
    infoWindow.open(marker.get('map'), marker); 
    }); 
    })(dl[i]); 
    marker.addListener('mouseout', function() { 
    infoWindow.close(); 
    }); 
} 
+0

嗨!只是供參考,我看到您要求編輯Theeternalpuzzle的答案,並投票拒絕編輯。不要編輯該答案來添加額外的代碼,而是將改進的代碼添加到自己的答案中會更好。 (歡迎來到StackOverflow並感謝您幫助您的開發人員!) –

0

我endend這樣做,並且它工作得很好

var myMarker=[]; 
var marker; 
for (i = 0; i < dl.length; i++) { 
    myMarker[i]=new google.maps.LatLng(lt[i], ln[i]); 
    marker = new google.maps.Marker({ 
    position: myMarker[i], 
    map: map 
    }); 
    attachSecretMessage(marker, dl[i]); 
} 


function attachSecretMessage(marker, secretMessage) { 
    var infowindow = new google.maps.InfoWindow({ 
    content: secretMessage 
    }); 

    marker.addListener('mouseover', function() { 
    infowindow.open(marker.get('map'), marker); 

    }); 

    marker.addListener('mouseout', function() { 
    infowindow.close(); 
    }); 

    }