如何在JSP中使用Google Map Api?

时间:2013-11-20 03:05:51

标签: javascript jsp google-maps google-maps-api-3

我正在关注Google Map API网页中的示例代码,该网页使用JavaScript和HTML。 HTML示例工作正常,但在JSP中使用JavaScript源创建Google地图不起作用。

  <%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script
    src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

这是来自documentation。如何在JSP Source中使用Google Api v3?

1 个答案:

答案 0 :(得分:9)

如果您上面发布的代码是您正在讨论的jsp,那么您错过了添加id为'map-canvas'的div。尝试类似下面的内容。

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
<script
    src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
 <div id="map-canvas" style="height:300px; width:500px"></div>
</body>
</html>

要正确渲染地图,必须有一个元素来保存它,并且该元素必须具有明确的高度和宽度。我希望这有帮助