首先,因为Location 是一个java 对象,所以你不能有一个名为long 的属性。此外,<div id="item"> insede forEach 将在 DOM 上生成具有重复 ID 的对象。
为了测试,我创建了一个像这样的Location 对象:
public class Location {
private double lat;
private double lng;
private String mapName;
private String name;
// getters and setters
}
以一种简单的方式,只需遍历 locations 以将位置添加到地图中,如下所示:
<c:forEach var="location" items="${locations}">
<h5>${location.name}</h5>
<div id="${location.mapName}" style="height: 180px; width: 400px;"></div>
</c:forEach>
然后迭代生成地图对象、标记等等,像这样:
<c:forEach var="location" items="${locations}">
var latLng_${location.mapName} = new gm.LatLng(${location.lat}, ${location.lng});
var options_${location.mapName} = {
zoom: 14,
center: latLng_${location.mapName},
mapTypeId: gm.MapTypeId.TERRAIN
};
var ${location.mapName} = new gm.Map(document.getElementById("${location.mapName}"), options_${location.mapName});
var marker_${location.mapName} = new gm.Marker({
title: "${location.name}",
position: latLng_${location.mapName},
map: ${location.mapName}
});
</c:forEach>
如果你愿意,你可以把它包含在一个函数中。在测试中,我生成了 4 张地图,如下图所示:
这是整个 JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
var gm = google.maps;
function initialize() {
<c:forEach var="location" items="${locations}">
var latLng_${location.mapName} = new gm.LatLng(${location.lat}, ${location.lng});
var options_${location.mapName} = {
zoom: 14,
center: latLng_${location.mapName},
mapTypeId: gm.MapTypeId.TERRAIN
};
var ${location.mapName} = new gm.Map(document.getElementById("${location.mapName}"), options_${location.mapName});
var marker_${location.mapName} = new gm.Marker({
title: "${location.name}",
position: latLng_${location.mapName},
map: ${location.mapName}
});
</c:forEach>
}
gm.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<c:forEach var="location" items="${locations}">
<h5>${location.name}</h5>
<div id="${location.mapName}" style="height: 180px; width: 400px;"></div>
</c:forEach>
</body>
</html>