我正在尝试使用asp.net将Google地图添加到我的网页。使用Google地图下面给出的代码显示几毫秒然后消失。我检查了控制台中的元素,并显示以下消息 - “未捕获类型错误:无法读取属性'样式'为null”。请指导我找到解决这个问题的方法。
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var control = document.getElementById('control');
control.style.display = 'block';
Uncaught TypeError: Cannot read property 'style' of null
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
答案 0 :(得分:0)
如果页面中不存在控制元素,则返回函数if (control===null) return;
答案 1 :(得分:0)
缺少标识为control
的元素。行后:
var control = document.getElementById('control');
变量control
获得了值null
,因此下一行
control.style.display = 'block';
产生错误:
Uncaught TypeError: Cannot read property 'style' of null
要解决此问题,您必须向ID为control
的网页添加新元素,例如:
<div id="control"></div>
如果您要向Google地图添加自定义控件,请检查文档Controls。