gpt4 book ai didi

javascript - 谷歌地图API,未捕获类型错误: Cannot read property 'offsetWidth' of null

转载 作者:行者123 更新时间:2023-12-03 08:20:24 24 4
gpt4 key购买 nike

我尝试在我的网页上创建一个按钮,一旦按下它,它就会出现一个带有谷歌地图的div框。但这不起作用!它出现了 javascript 语法错误“Uncaught TypeError: Cannot read property 'offsetWidth' of null”,请帮忙!

chrome 开发工具出现 JavaScript 语法问题。这是我第一次在我的网页上使用 Google map API。

<! DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Google book search </title>
<!--link rel="stylesheet" href="css/style.css"-->
</head>

<body>
<div id = "input">
<form>
<input type="button" id="search_button" value="search">
</form>
</div>

</body>

</html>

<script >
var body = document.getElementsByTagName("body")[0];
var dosearch= function() {

var newDiv =document.createElement("div");
newDiv.setAttribute("id", "map");
newDiv.style.width="100px";
newDiv.style.height="100px";
body.appendChild(newDiv);
};

window.onload=function(){
console.log("ready");
var search_button= document.getElementById("search_button");
search_button.addEventListener("click", dosearch);
}
</script>

<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDpKAwq-qKxzm-9D1405KCFp7ZTtu_Vimg&callback=initMap"
async defer></script>

最佳答案

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null中所示,您需要在调用 initMap 之前将 id="map"的 div 附加到 DOM。

最简单的修复:将 div 附加到 DOM 后调用 initMap 函数(在 dosearch 函数内):

var dosearch = function () {
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "map");
newDiv.style.width = "100px";
newDiv.style.height = "100px";
body.appendChild(newDiv);
initMap();
};

working fiddle

代码片段:

var body = document.getElementsByTagName("body")[0];
var dosearch = function() {
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "map");
newDiv.style.width = "100px";
newDiv.style.height = "100px";
body.appendChild(newDiv);
initMap();
};

window.onload = function() {
console.log("ready");
var search_button = document.getElementById("search_button");
search_button.addEventListener("click", dosearch);
}
var map;

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
}
<script src="https://maps.googleapis.com/maps/api/js" async defer></script>
<div id="input">
<form>
<input type="button" id="search_button" value="search" />
</form>
</div>

关于javascript - 谷歌地图API,未捕获类型错误: Cannot read property 'offsetWidth' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33770539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com