2012-06-08 36 views
0

我試圖在Google Map上使用綁定到每個標記的InfoWindows使用JSON放置多個標記。不幸的是,只有一個標記出現,這是JSON中的最後一個值。沒有其他標記會顯示,漫畫氣球樣式的箭頭不會出現在InfoWindow後面。已經嘗試了很長時間來解決這個問題,但沒有任何工作。將InfoWindows放置在Google Map標記上的問題

這是代碼:

var stories = {{story_Json|safe}}; 

var map; 


function loadMarkers(stories){ 
    for (i=0;i<stories.length;i++) { 
     var story = stories[i]; 
     var point = new google.maps.LatLng(story.latitude, story.longitude); 
     var marker = new google.maps.Marker({position: point, map: map}); 
     var infowindow = new google.maps.InfoWindow({ 
      content: '<div >'+ 
       '<div >'+ 
       '</div>'+ 
       '<h2 class="firstHeading">'+story.headline+'</h2>'+ 
       '<div>'+ 
       '<p>'+story.copy+'</p>'+ 

       '</div>'+ 
       '</div>' 

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

    } 
} 


function mainMap(position) 
{ 
     // Define the coordinates as a Google Maps LatLng Object 
     var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 

     // Prepare the map options 
     var mapOptions = 
     { 
        zoom: 15, 
        center: coords, 
        mapTypeControl: false, 
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 

     // Create the map, and place it in the map_canvas div 
     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 

     // Place the initial marker 
     var marker = new google.maps.Marker({ 
        position: coords, 
        map: map, 
        title: "Your current location!" 
     }); 

     loadMarkers(stories); 

    } 

任何深入瞭解這些問題大加讚賞。

回答

1

InfoWindow使用i的最後一個值保留引用(因爲循環結束,我們看到JSON的最後一個值)。這與Javascript中的函數範圍有關,而不是塊範圍。

獲得預期結果的一種方法是引入一個新的story來引用每個infowindow的每個故事值。這可以用一個新的匿名功能範圍進行:

function loadMarkers(stories){ 
    for (i=0;i<stories.length;i++) { 
     var story = stories[i]; 

     (function(story) { 
      var point = new google.maps.LatLng(story.latitude, story.longitude); 
      var marker = new google.maps.Marker({position: point, map: map}); 
      var infowindow = new google.maps.InfoWindow({ 
      content: '<div >'+ 
       '<div >'+ 
       '</div>'+ 
       '<h2 class="firstHeading">'+story.headline+'</h2>'+ 
       '<div>'+ 
       '<p>'+story.copy+'</p>'+ 

       '</div>'+ 
       '</div>' 

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

忘了信息窗口的箭頭,這是顯示不正確,如模糊或變形?也許這是一個CSS的東西,添加這些行可能會幫助你。

#map_canvas label { width: auto; display:inline; } 
#map_canvas img { max-width: none; max-height: none; } 
+0

謝謝,Heitor。這似乎工作。無法關閉infowindow,但這是另一個問題。箭頭是唯一沒有出現的東西,但我會嘗試CSS解決方案。箭頭正在丟失;不知道爲什麼。 –

+0

如果您在infowindows的右上角沒有看到x,並且無法關閉它,則這可能與氣球箭頭未出現相關。你使用WordPress還是CMS?我讀到了與CMS一起使用時變形的谷歌地圖組件,因此我鼓勵您嘗試CSS修復,如果它無效,我建議發佈圖片。 –

+0

不,我沒有看到x。我正在使用Django。也許這是相關的。 –

相關問題