我正在使用Google Maps JS Api在网站上显示地图。该网站向我显示一张空卡,在检查元素时,我发现错误:无法读取null的属性'offsetwidth'。
如果有人能够帮助我,我将不胜感激!我在下面添加了所有相关的编码。
CSS
.content {
position: fixed;
top: 15%;
width: 100%;
height: 85%;
overflow: auto;
}
.card {
width: 85%;
height: auto;
margin-left: auto;
margin-right: auto;
box-shadow: 0 2px 6px #888888, 0 2px 6px #888888;
}
.card-map {
width: 100%;
height: 300px;
}
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../style.css">
</head>
<body>
<div class="content">
<div class="card">
<div class="card-map"></div>
<script type="text/javascript" src="../google-maps.js"></script>
</div>
</div>
</body>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDb8GJ8wzza1nQyrYBUf4iKBzF1TcC6BXA&callback=initMap"></script>
</body>
JS
function initMap() {
var customMapType = new google.maps.StyledMapType([{
"featureType": "administrative",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.attraction",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.business",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.government",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.medical",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.park",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.place_of_worship",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.school",
"stylers": [
{ "visibility": "off" }
]},{
"featureType": "poi.sports_complex",
"stylers": [
{ "visibility": "off" }
]},{
name: 'Custom Style'
}]);
var customMapTypeId = 'custom_style';
var map = new google.maps.Map(document.getElementById("card-map"), {
zoom: 12,
center: {lat: 40.674, lng: -73.946},
disableDefaultUI: true,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, customMapTypeId]
}
});
var marker = new google.maps.Marker({
position: {lat: 40.674, lng: -73.946},
map: map,
});
map.mapTypes.set(customMapTypeId, customMapType);
map.setMapTypeId(customMapTypeId);
window.addEventListener("load",initMap, false);
}
答案 0 :(得分:0)
我认为问题在于您在页面完成加载之前(在创建card-map
元素之前)尝试初始化地图。
试试这个:
删除此行
google.maps.event.addDomListener(window, "load", initialize);
来自initialize
函数
并在该函数之外添加此函数(在全局上下文中)。
window.addEventListener("load",initialize, false);
此外,删除对initialize
功能的所有其他调用。
答案 1 :(得分:0)
我发现了这个问题:我使用的是一个类而不是一个id。在css和html中将类更改为id确实解决了问题。