【问题标题】:google map not showing in page by ajax loaded content谷歌地图未通过ajax加载的内容显示在页面中
【发布时间】:2015-12-02 06:30:49
【问题描述】:

我有 main.html 页面,我正在调用 main.html 中的子页面,如下所示:

main.html

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<script type="text/javascript">
function getmyurl(url){
$('#mypageload').load(url);
}
</script>
<a href="javascript:void(0);" onclick="getmyurl('googlemap.htm');">google map</a>
<div id="mypageload">html page content will come to here like php include</div>
</body>
</html>

这适用于普通页面。但是谷歌地图(googlemap.htm)没有显示地图。我猜这里有问题:

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

我可以做些什么来解决问题?

googlemap.htm

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
</head>
<body>
<script>
function initialize() {
....
}
</script>
<div id="map-canvas"></div>
</body>
</html>

注意:我的英语不好,对不起。

【问题讨论】:

    标签: html google-maps google-maps-api-3


    【解决方案1】:

    您的代码出现的错误(我可以复制它最好)是:

    在“文档”上执行“写入”失败:除非明确打开,否则无法从异步加载的外部脚本写入文档。

    你可以通过asynchronously loading the API解决这个问题:

    function loadScript(src,callback){
    
      var script = document.createElement("script");
      script.type = "text/javascript";
      if(callback)script.onload=callback;
      document.getElementsByTagName("head")[0].appendChild(script);
      script.src = src;
    }
    loadScript('http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialize');
    

    proof of concept fiddle

    【讨论】:

    • 感谢您的回答和有用的示例。我现在解决了我的问题。
    • 您的建议对我不起作用,但无论如何,您的示例代码中似乎有错字。回调应该是第二个参数,而不是查询字符串的一部分。
    【解决方案2】:

    由于 Google 地图支持 异步 加载,您可以通过应用以下更改来实现它:

    替换googlemap.htm文件中的行:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    

    <script src="https://maps.googleapis.com/maps/api/js?callback=initialize&sensor=false&libraries=places" async defer></script>
    

    由于callback 参数指定加载谷歌地图库后调用的函数的名称,在googlemap.htm 文件中注释(或删除):

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

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 2019-07-27
      • 2012-09-23
      • 1970-01-01
      相关资源
      最近更新 更多