简体   繁体   中英

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

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:

<body onload="initialize()">

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

<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?

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:

<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.

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:

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

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


...more html
</body>

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

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

You can call following way as well

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM