【发布时间】:2017-08-03 03:38:31
【问题描述】:
我正在尝试设置一个系统,使谷歌地图出现在弹出 iframe [使用 Fancybox] 中,我已阅读 a lot of similar topics on Stack Overflow 并且我已经实施了他们的许多建议,但没有成功。
问题是:
Uncaught ReferenceError: google is not defined
加载 iframe 时。 iframe 正确加载其数据(可以在浏览器控制台上查看),但 Google 地图无法显示,并且控制台错误(上图)表明它无法初始化。
我已经尝试过或不适用的一些事情:
- 我设置了回调函数
- 我使用的是 Javascript Map API 而不是
v3版本。 - 我尝试了
async和defer都没有成功。 - 我不希望地图成为 iframe 的唯一内容(嵌入式 Google 地图)。
- 我尝试使用窗口加载 javascript 事件检测器但没有成功(来自另一个问题)。
- 问题不在于 iframe 本身 - 有效 - 在于框架与其父级之间的关系。
令人讨厌的是,这个弹出式地图系统在经过一个小时的反复试验后运行良好,然后我清除了我的浏览器历史记录(或做了其他事情),这意味着问题已经再次出现并且不会消失。
iframe 页面:
<h1> Some Dynamic title </h1>
<div id="map_canvas"></div>
<div> Some other content </div>
<script type="text/javascript" async defer
src="https://maps.googleapis.com/maps/api/js?key=<mykey>®ion=GB&callback=initmap"></script>
<script type="text/javascript" >
/**
Imported idea from another Question on Stackoverflow (didn't work):
window.addEventListener('load',function(){
if(document.getElementById('map_canvas')){
initmap();
}
},false);
**/
var map;
function initmap() {
var myOptions = {
zoom: 11,
center: {lat: 5.345617, lng: 10.562},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var places=[];
var memnames=[];
var memid=[];
var teams=[];
var address=[];
<?php
print $mapOut; //data output to map markers.
?>
var infoWindow;
for(var i=0 ; i<places.length ; i++){
var iconBase = 'https://<?php print $_SERVER['SERVER_NAME'];?>/images/site/';
var marker=new google.maps.Marker({
position: places[i],
map: map,
title: memnames[i],
icon: iconBase + 'rugby-player-4.png'
});
(function(i,marker){
google.maps.event.addListener(marker, 'click', function(){
if(!infoWindow){
infoWindow = new google.maps.InfoWindow();
}
var content='<div class="mapInfo">'+
'<a href="/details.php?memid='+memid[i]+'">'+memnames[i]+'</a><strong>'+teams[i]+'</strong>'+address[i]+'</div>';
infoWindow.setContent(content);
infoWindow.open(map,marker);
});
})(i,marker);
}
}
/***
google.maps.event.addDomListener(window, 'load', initmap);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
***/
</script>
更多详情:
直接访问地图页面,如果我先加载谷歌地图脚本,我会得到响应;它告诉我initmap is not a function,然后如果我第二次加载它(async/defer)它告诉我google is not defined。
此地图页面 javascript 代码与其他网站上使用的完全相同(没有 ajax/iframe 调用)并且可以正常工作。
我知道这听起来像 de ja vu 的其他 Google 地图问题,但我看到的问题无法解决这个问题。
【问题讨论】:
标签: javascript google-maps iframe