2011-08-08 62 views
0

試圖簡化我的谷歌地圖自定義代碼,把標記和信息氣泡。然而,遇到了幾個我似乎無法調試代碼的問題,目前它沒有輸出任何內容。代碼定義經緯度/標題和內容,然後在地圖上輸出它們作爲標記。谷歌地圖 - 自定義JS輸出infowindows和標記問題

<script type="text/javascript"> 

    function initialize() { 
    var myLatlng = new google.maps.LatLng(20,0); 
    var myOptions = { 
     zoom: 2, 
     center: myLatlng, 
     mapTypeId: google.maps.MapTypeId.TERRAIN 
    } 

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

var countries = [ 
    {title:'Afghanistan', lat:34.28, lon:69.11, content:"<h2>Afghanistan</h2><p>16 Alumni</p>"}, 
    {title:'Albania', lat:41.18, lon:19.49, content:"<h2>Albania</h2><p>7 Alumni</p>"}, 
    {title:'Angola', lat:-8.5, lon:13.15, content:"<h2>Angola</h2><p>9 Alumni</p>"}, 
    {title:'Antarctica', lat:-80, lon:0, content:"<h2>Antarctica</h2><p>1 Alumnus</p>"}, 
    {title:'Antigua & Barbuda', lat:17.20, lon:-61.48, content:"<h2>Antigua & Barbuda</h2><p>1 Alumnus</p>"}, 
    {title:'Argentina', lat:-36.30, lon:-60, content:"<h2>Argentina</h2><p>29 Alumni</p>"}, 
]; 

for (i=0;i<countries.length;i++) 
{ 
    c = countries[i]; 
    marker: new google.maps.Marker({position: new google.maps.LatLng(" + c['lat'] + "," + c['lon'] + "), map: map, title: '" + c['title'] + "'}), 
    infowindow: new google.maps.InfoWindow({content: '" + c['content'] + "'}); 
} 

var item; 
for (var i=0; i<countries.length; i++) { 
    item = countries[i]; 
    google.maps.event.addListener(item.marker, 'click', makeCallback(item)); 
} 

function makeCallback(country) { 
    return function() { 
     country.infowindow.open(map, country.marker); 
    }; 
} 

}

</script> 

回答

0

有所述代碼的不同排版和語法錯誤。也不需要在變量的地方構造字符串。以下是一個工作版本:

... 
var countries = [...]; 

for (var i = 0; i < countries.length; i++) { 
    var c = countries[i]; 
    c.marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(c.lat, c.lon), 
     map: map, 
     title: c.title}); 
    c.infowindow = new google.maps.InfoWindow({content: c.content}); 

    google.maps.event.addListener(c.marker, 'click', makeCallback(c)); 
} 

function makeCallback(country) { 
    return function() { 
     country.infowindow.open(map, country.marker); 
    }; 
} 
+0

哇謝謝,看起來我做的比我想象的更多的錯誤,非常感謝您的幫助! – Nick

+0

我很樂意幫助你。如果您對我的回答滿意,您可以給我投票(號碼上方的箭頭 - 號碼會增加)並接受我的回答(號碼下面的複選標記 - 複選標記變爲綠色)。 – Jiri