Search code examples
javascriptgoogle-mapsprototypejs

How do I provide a non-global callback when loading Google Maps API?


I am only able to download the Google Maps v3 API when the callback is a global function:

function onMapLoad() {
    alert('API is loaded');
}

var script = new Element(
    'script', {
        type: 'text/javascript',
        src: 'http://maps.googleapis.com/maps/api/js?key=' 
            + Map.API_KEY
            + '&sensor=false&callback=onMapLoad'
    }
);

document.body.appendChild(script);

I don't want to use a global function. Instead I want to call a method on a singleton: Map.instance().onLoaded.

// ...
+ '&sensor=false&callback=Map.instance().onLoaded'
// ...

When I attempt to do this, there is a NetworkError: 403 Forbidden on loading Google's scripts. This seems to imply that Google's service did not like my callback function string. There's no problem with the callback function itself.


Solution

  • Try using the google loader call

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    google.load("maps", "3", {"other_params": "sensor=false","callback" : Map.instance().onLoaded });

    https://developers.google.com/loader/