Google地图API,Uncaught TypeError:无法读取属性' offsetWidth'为null

时间:2015-11-18 02:00:39

标签: javascript google-maps

我按下它后会尝试在我的网页上创建一个按钮,它会显示一个带有谷歌地图的div框。但它不起作用!它出现了javascript语法Error" Uncaught TypeError:无法读取属性' offsetWidth' of null"请帮忙!

Chrome开发工具,出现了javascript语法问题。这是我第一次在我的网页上使用Google地图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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:0)

使用

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>

在您的资源中。