javascript - 谷歌地图未捕获类型错误 : Cannot read property 'LatLng' of undefined

标签 javascript api google-maps

我不断收到此错误“未捕获的类型错误:无法读取未定义的属性‘LatLng’” 尝试创建 map 时
在头部:

 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"/>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true"></script>

................

function init(){


            var latlng = new google.maps.LatLng(-43.552965, 172.47315);
            var myOptions = {
                zoom: 10,
               center: latlng,
               mapTypeId: google.maps.MapTypeId.ROADMAP

            };
           map = new google.maps.Map(document.getElementById("map"), myOptions);


        }

................

    <body>
        <div id="map" style="width:600px;height: 600px;">
        </div>
        <ul class="navigation">
        </ul>
    </body>

最佳答案

如果一起使用,上面的两个答案将解决这个问题。属性 LatLng 未定义,因为 google对象尚不可用。

你总是关闭你的 <script>标签期。

google在加载 DOM 之前,对象不可用。所以在你的javascript中你必须使用谷歌地图的addDomListener() . Kara 的解决方案是正确的,但它在您的情况下不起作用,因为函数名称是 init 并且 addDomListener 必须等待“加载”。你需要:

google.maps.event.addDomListener(window, 'load', init);

另一个非常简单的解决方案是将回调添加到脚本

src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true&callback=init

回调将等待脚本加载,然后触发您的 init初始化和绘制 map 的函数。

我把解决方案放在 CodePen 上 http://codepen.io/redbirdisu/pen/BHivq

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

相关文章:

php - 选择距离最小的随机 GPS 点

javascript - 谷歌地图 API : Adding letters to my markers on my google map

javascript - PowerBI-Javascript嵌入式仪表板不是 "clickable"(钻取关联报告等)

Python - Flask 导入后无法识别

javascript - 无法从 Express Route 查询 MySQL 数据库

php - YouTube PHP API: session 状态与NULL字符串(10) “1494600193”不匹配

android - 在 React Native AirBnb 的 MapView [Android] 上关注用户位置

javascript - 未定义的函数与javascripts

javascript - 如何在 iphone uiwebview 中处理 iframe/frames dom

javascript - 通过AJAX/PHP设置变量提交URL,无需刷新页面,加载变量