我希望在jsp页面上将标记传递给javascript以在谷歌地图上显示它们。 在servlet中我从数据库加载标记数组,但我不知道如何将它们传递给javascript。 这是我的servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) `throws ServletException, IOException {
// TODO Auto-generated method stub`
PlaceDao placeDao = new PlaceDao();
ArrayList<Place> pList = new ArrayList<Place>();
try {
pList = placeDao.readData();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Marker marker = new Marker();
ArrayList<Marker> mList = new ArrayList<Marker>();
for (int i = 0; i < pList.size(); ++i)
{
marker.setLatitude(pList.get(i).getLatitude());
marker.setLongitude(pList.get(i).getLongitude());
mList.add(marker);
}
request.setAttribute("marker", mList);
request.getRequestDispatcher("pages/location.jsp").forward(request, response);
}`
和我的jsp页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
function initialize() {
var mapProp = {
center : myCenter,
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),
mapProp);
var marker = new google.maps.Marker({
position : myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width: 500px; height: 380px;"></div>
</body>
</html>
而不是var myCenter = new google.maps.LatLng(51.508742, -0.120850);
我想传递我的数组。我认为可以用JSON完成,但我不确定并且不知道如何做。
谢谢你的帮助!
答案 0 :(得分:0)
很少有事情需要注意:
List
。 您可以从以下两个选项中选择一个:
使用Ajax调用(例如):
$.get( "urlToMethod", {
"someVariable": someValue
}).done(function( data ) {
// in data you have the list of markers
}).error(function (data) {
// in data you have exception or the error
});
Java映射:
@RequestMapping(value = "urlToMethod")
public String[] getMarkers (
HttpServletRequest httpRequest,
HttpServletResponse httpResponse,
@RequestParam(value = "someVariable") String someVariable) {
// get the markers and return a String[] or JSONArray!!!
}
将列表放入JSP中并在脚本中读取它:
Java端(必要时创建HelperClass
)
model.addAttribute("markers", markersList);
的Javascript
markers = $("#markers").val();
JSP
<form:hidden path="markers" id="markers" />
List
:此处您还可以使用以下任何选项:
String
或String[]
(请勿使用double或float作为GPS lat / long,因为精度不足)。 注意:我假设您的项目中有JQuery
,也要小心,因为在Ajax解决方案Spring
中使用了check here if you don't have it in your project。