Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot add Google Map API script after pageload

Due to some limitations, I cannot have the script tag for the Google Map API available on page load. I have tried adding the script to the page many different ways, including using jQuery to add a script tag like so:

$('head').append('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>');

I have also tried to include it in a more manual way, like so:

var script = document.createElement("script");
script.src = 'http://maps.google.com/maps/api/js?sensor=false';
script.type = "text/javascript";
document.head.appendChild(script);

Both of these examples cause the entire page to become white and blank. Any thoughts on how I can do this?

like image 261
Jessie A. Morris Avatar asked Jun 26 '10 18:06

Jessie A. Morris


People also ask

Why isn't my Google Maps API working?

There are a several reasons why your google maps may not be working, the most common issue being no Google Map API key set or set incorrectly. To use the Google Maps JavaScript API, you must register your app project on the Google Cloud Platform Console and get a Google API key which you can add to your app.

How do I resolve this page Cannot load Google Maps correctly?

Unless a valid API key is present, the map will be displayed in a lower resolution and will have a watermark on it. If the credit card linked to the account is invalid or the number of free map views is surpassed, the "This Page Can't Load Google Maps Correctly" error will show up.

How do you check if Google Maps API is loaded?

maps) {...} will give you a reference error if google is undefined (i.e. if the API didn't load). Instead, use if (typeof google === 'object' && typeof google. maps === 'object') {...} to check if it loaded successfully.


5 Answers

This is what worked for me (following JAM's comment) - just run function after page load

function writeGoogleMapsScript()
{
        document.oldWrite = document.write; 
        document.write = function(text)
        {                                 
            var parser = new DOMParser();
            var element = parser.parseFromString(text, "text/xml");           
            var child = element.firstChild;                
            var element = document.createElement("script");
            element.src = child.getAttribute('src');
            element.type= "text/javascript";            
            document.getElementsByTagName("head")[0].appendChild(element);                          
            document.write = document.oldWrite;
        };                         
        var element = document.createElement("script");
        element.src = "http://maps.google.com/maps/api/js?sensor=true&language=iw";
        element.type= "text/javascript";            
        document.getElementsByTagName("head")[0].appendChild(element);  
}
like image 152
Cesar Avatar answered Oct 06 '22 15:10

Cesar


If you look at the JavaScript returned by the URL you're trying to load from Google, you'll see it contains a document.write() statement:

http://maps.google.com/maps/api/js?sensor=false

function getScript(src) {
    document.write('<' + 'script src="' + src + '"' +
                   ' type="text/javascript"><' + '/script>');
}

document.write() is a command that's only available during page load. It cannot be called afterwards, or you will experience those results that you mention. Google doesn't want you to load this particular script after the page load.

Dare I say it? Perhaps you need to inject an iframe that points to a page with the google maps code setup so document.write() can work as they designed it.

like image 31
a7drew Avatar answered Oct 06 '22 15:10

a7drew


I belive Fabio Pozzi's answer is the correct solution to this, in addition to his answer here is a snippet of code using jQuery.getScript to load both the google api loader and maps.

            // load the google api loader
            if( typeof(google) == 'undefined' || !google.load ) {
                $.getScript( '//www.google.com/jsapi', function() {
                    loadMaps();
                });
            }

            // otherwise just load maps
            else {
                loadMaps();
            }

            // load the google maps api
            function loadMaps() {
                google.load("maps", "3", {
                    callback: initMap,
                    other_params: 'sensor=true'
                });
            }
like image 25
3urdoch Avatar answered Oct 06 '22 15:10

3urdoch


I will answer even if the question is a bit old. I think you should use the google api

google.load

following this documentation google api loader. To do this you need a google api key and you need to include the script to use them in your page source. After that you can use a callback to load the map.

like image 28
Fabio Pozzi Avatar answered Oct 06 '22 15:10

Fabio Pozzi


I do realize that this is old question but the following solution works for me: Then adding script to page you should provide callback parameter and then lazy loading and inclination works for Google Maps. Here follows the example:

 $('body').append('<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=XXX-YYYY-ZZZ&sensor=false&callback=initializeGoogleMaps"></script>');
 window.initializeGoogleMaps = function () {
 }
like image 27
Darius Kucinskas Avatar answered Oct 06 '22 15:10

Darius Kucinskas