[英]Google Maps Api 3: Uncaught TypeError: Cannot call method 'setCenter' of undefined
[英]Google Maps JS: Uncaught TypeError: Cannot call method 'addDomListener' of undefined
我收到google.maps.event.addDomListener(window, 'load', initialize);
的“ 无法调用未定义的方法'addDomListener' ”的错误google.maps.event.addDomListener(window, 'load', initialize);
代码行,其中event
为“未定义”。 我的以下代码基本上是从developer.google.com上的示例复制而来的。
$(function () {
var officeMap = $("#map-canvas");
if (officeMap.length > 0) {
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644), zoom: 8
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
}
});
google maps脚本(带有API密钥)在此之前在文档正文末尾(使用Modernizr)加载,如下所示:“ https://maps.googleapis.com/maps/api/js?key=myApiKey&sensor= false “(我用生成密钥ofc切换“ myApiKey” :)
该错误是否表示Google Maps脚本未首先加载? 还是我的API密钥无效? 或者是其他东西?
谷歌代码示例是正确的,但考虑到存在ajax脚本加载,因此不会在大多数网站上运行。 是的,您是对的,在调用函数时尚未加载google脚本。
看看该Google脚本的来源,它不是完整的javascript SDK,它只是一个代理/启动文件。 我记得那些样例代码没有问题时,这并不是最后一次。
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>
<script>
function initialize() {
var officeMap = $("#map-canvas");
if (officeMap.length > 0) {
var map;
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644), zoom: 8
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
}
</script>
尝试使用它代替您的密钥
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false">
我的密码
var myCenter=new google.maps.LatLng(-34.397, 150.644);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:8,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById('maparea'),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
title:'Hi'
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:'',
boxStyle: {
maxHeight:200
}
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.