jQuery 谷歌地图 API 的初始化函数没有 ONLOAD 正文标签或在结束正文之前

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15411309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:59:14  来源:igfitidea点击:

Google Maps API's initialize function without ONLOAD body tag or before end body

javascriptjqueryhtmlgoogle-maps-api-3

提问by Jason

I'm working on a website that uses the DotNetNuke CMS. I've added a Google Maps map using the API, but I need to call the initialize() function when the page has loaded. Usually you'd do this with:

我正在使用 DotNetNuke CMS 的网站上工作。我已经使用 API 添加了 Google Maps 地图,但是我需要在页面加载时调用 initialize() 函数。通常你会这样做:

<body onload="initialize()">

or add the following just before the < /body> tag:

或者在 </body> 标签之前添加以下内容:

<script type="text/javascript">
    window.onload = function () {
        initialize();
    }
</script>

I however do not have access to the body tag, or exact end of the tag. Is there any other way to call this function without doing the aforementioned?

但是,我无法访问正文标签或标签的确切结尾。有没有其他方法可以在不执行上述操作的情况下调用此函数?

回答by Adam

Not a good idea to do this on a window load event - if you've got some high-latency images or other assets loading then your google map will load very slowly. Just before the closing body tag, add this:

在窗口加载事件上执行此操作不是一个好主意 - 如果您加载了一些高延迟图像或其他资产,那么您的谷歌地图加载速度会非常缓慢。在结束 body 标记之前,添加以下内容:

<script>
 initialize();
</script>

All that google needs to be ready before it builds it's map is the DOM, not every single asset on the page. The DOM is always fully loaded by the time the script loads right before the closing body tag.

谷歌在构建地图之前需要准备的只是DOM,而不是页面上的每一个资产。DOM 总是在关闭 body 标签之前脚本加载时完全加载。

EDIT

编辑

Technically, all that google maps needs to be ready before it builds it's map is the div that it is going to be placed in. So you don't even need to have the script before your closing body tag, you could have it immediately after your map div tag like this:

从技术上讲,谷歌地图在构建它的地图之前需要准备好的就是它要放置的 div。所以你甚至不需要在关闭 body 标签之前拥有脚本,你可以在之后立即拥有它你的地图 div 标签是这样的:

<html>
...
<body>
...html...

<div id="map-canvas"></div>
<script>initialize();</script>


...more html
</body>

回答by Jason

I've figured out when I was just randomly trying something. Matter of adding the following to the headers. Long live API V3!

当我只是随机尝试一些东西时,我已经弄清楚了。将以下内容添加到标题的问题。API V3 万岁!

<script type="text/javascript">
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

回答by Jason

You can call following way as well

您也可以通过以下方式调用

    <div id="map-canvas"></div>

    $("#map-canvas").on("load", function () {
       initialize();            
    });