Google MAP API Uncaught TypeError: Cannot read pro

2019-01-01 01:47发布

I'm trying to use Google MAP API v3 with the following code.

<h2>Topology</h2>

<script src="https://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

<link rel="stylesheet" type="text/css" href="{% url css_media 'tooltip.topology.css' %}" />
<link rel="stylesheet" type="text/css" href="{% url css_media 'tooltip.css' %}" />

<style type="text/css" >
      #map_canvas {
              width:300px;
            height:300px;
     }
</style>

<script type="text/javascript">

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);

</script>

<div id="map_canvas"> </div>

When I run this code, the browser says this.

Uncaught TypeError: Cannot read property 'offsetWidth' of null

I have no idea, since I follow the direction given in this tutorial.

Do you have any clue?

25条回答
刘海飞了
2楼-- · 2019-01-01 02:25

Check that you're not overriding window.self

My issue: I had created a component and wrote self = this instead of var self = this. If you don't use the keyword var, JS will put that variable on the window object, so I overwrote window.self which caused this error.

查看更多
若你有天会懂
3楼-- · 2019-01-01 02:27
  • Setup ng-init=init() in your HTML
  • And in the controller

    use $scope.init = function() {...} instead of google.maps.event.addDomListener(window, "load", init){...}

Hope this will help you.

查看更多
梦该遗忘
4楼-- · 2019-01-01 02:29

For even more others that might still be having this issue, I was using a self-closing <div id="map1" /> tag, and the second div was not showing, and did not seem to be in the dom. as soon as i changed it to two open&close tags <div id="map1"></div> it worked. hth

查看更多
梦寄多情
5楼-- · 2019-01-01 02:30

In my case these sort of issues were solved using defer https://developer.mozilla.org/en/docs/Web/HTML/Element/script

<script src="<your file>.js" defer></script>

You need to take into account browsers's support of this option though (I haven't seen problems)

查看更多
泪湿衣
6楼-- · 2019-01-01 02:32

google uses id="map_canvas" and id="map-canvas" in the samples, double-check and re-double-check the id :D

查看更多
一个人的天荒地老
7楼-- · 2019-01-01 02:32

My fail was to use

zoomLevel

as an option, rather than the correct option

zoom
查看更多
登录 后发表回答