2012-12-17 141 views
1

我正在使用Google maps API和JSP創建應用程序。我有一個問題,因爲當我將一個事件添加到標記並使用查詢字符串傳遞值時,我總是得到相同的值,而不是標記的實際值。有人能讓我知道我做錯了什麼嗎?谷歌地圖JSP

<% 

      Query query2 = em.createNamedQuery("Factories.findAll"); 
      List<Factories> factories = query2.getResultList(); 

      for (int i = 0; i < factories.size(); i++) { 
       Float longitude = factories.get(i).getLongitude(); 
       Float latitude = factories.get(i).getLatitude(); 
       String name = factories.get(i).getName(); 
       Integer id = factories.get(i).getFactoryID(); 
     %> 

       var marker = new google.maps.Marker({ 
        position: new google.maps.LatLng(<%=latitude%>, <%=longitude%>), 
        raiseOnDrag:true, 
        title: "<%=name%>", 
        clickable:true, 
        zIndex: <%=id%>, 
        map: map 
       }); 
       google.maps.event.addListener(marker, 'click', function() { 
        window.location = "viewFireworksFactory.jsp?id=" + marker.getZIndex(); 
       }); 

     <% }%> 
+0

使用scriptlets是第一個錯誤,使用jstl標籤,而不是 – NimChimpsky

回答

1

查看生成的JavaScript。它看起來像下面這樣:

var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(245, 654), 
       raiseOnDrag:true, 
       title: "A", 
       clickable:true, 
       zIndex: 1, 
       map: map 
      }); 
google.maps.event.addListener(marker, 'click', function() { 
    window.location = "viewFireworksFactory.jsp?id=" + marker.getZIndex(); 
}); 

var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(654, 987), 
       raiseOnDrag:true, 
       title: "B", 
       clickable:true, 
       zIndex: 2, 
       map: map 
      }); 
google.maps.event.addListener(marker, 'click', function() { 
    window.location = "viewFireworksFactory.jsp?id=" + marker.getZIndex(); 
}); 

var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(985, 2315), 
       raiseOnDrag:true, 
       title: "C", 
       clickable:true, 
       zIndex: 3, 
       map: map 
      }); 
google.maps.event.addListener(marker, 'click', function() { 
    window.location = "viewFireworksFactory.jsp?id=" + marker.getZIndex(); 
}); 

var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(6855, 464), 
       raiseOnDrag:true, 
       title: "D", 
       clickable:true, 
       zIndex: 4, 
       map: map 
      }); 
google.maps.event.addListener(marker, 'click', function() { 
    window.location = "viewFireworksFactory.jsp?id=" + marker.getZIndex(); 
}); 

所以,在明確,將重新定義相同的標記變量N倍,覆蓋同一變量以前的定義。並且所有聽衆將因此獲得分配給該變量的最後一個對象引用的標記中的Z索引。

+0

它是有道理的,但由於所有標記出現在地圖上,我認爲它並非如此。是否有可能改變每個循環的變量名稱? – user1911104

+0

您可以將每次迭代時遞增的計數器的值附加到每個標記變量。或者你可以將每個循環放入一個閉包:'(function(){var marker = ...; google.maps.event.addListener ...;})();' –

+0

工作...謝謝:) – user1911104