我正在制作一个 ASP.NET Webforms 页面,它将显示一个包含一系列标记的谷歌地图(通过 Google Maps JavaScript API )。
如果我不”将 <div id="map-canvas">
放在 <form>
标签内,效果会很好。
但是如果我搬家<div id="map-canvas">
里面<form>
我只是得到一个空白页(没有错误)。
查看检查器中的空白页,看起来好像 <div id="map-canvas">
正在填充一些基本元素来显示 map (标记除外),但页面根本不显示任何内容。
这可能是由 document.getElementById
引起的由于 <form id="form1" runat="server">
上动态创建的 ID 导致遍历 DOM 时出现问题?
注意:提供的代码只是一个测试页。一旦我对其进行排序,它将使用 ASP.NET MasterPage。
CSS
<style type="text/css">
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px;
}
脚本
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latlngCenter = new google.maps.LatLng(30.000000, -100.000000);
var mapOptions = { zoom: 3, center: latlngCenter }
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var latlngPlaceOne = new google.maps.LatLng(-30.000000, 150.000000);
var markerPlaceOne = new google.maps.Marker({
position: latlngPlaceOne,
map: map,
title: 'Place One'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
HTML
<body>
<form id="form1" runat="server">
<div id="map-canvas"></div>
</form>
</body>
最佳答案
我已经尝试过您的示例,只需稍加修改即可工作:可能只是您的表单尺寸“缩小”,因此 map 不可见。我添加了以下样式(大部分取自 this 示例):
<style>
html, body, form, #map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
</style>
希望这有帮助。
关于javascript - document.getElementById 未在 ASP.NET 表单中找到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21250015/