How to load Google Maps API with RequireJS?

hjuster picture hjuster · Apr 3, 2013 · Viewed 35.5k times · Source

I am struggling to load gmaps api with requireJS . This is what I've tried:

requirejs.config({
    urlArgs: "noCache=" + (new Date).getTime(),
    paths : {
        "jquery": "vendor/jquery-1.8.2.min",
        "bootstrap": "vendor/bootstrap.min",      
        "underscore": "libs/underscore-min",
        "backbone": "libs/backbone-min",    
        "template": "libs/template",
        "gmaps": "http://maps.google.com/maps/api/js?v=3&sensor=false"
    },
    shim: {
        'backbone': {
            deps: ['jquery', 'underscore'],
            exports: 'Backbone'
        },
        'underscore': {
            exports: '_'
        },
        'bootstrap': {
            deps: ['jquery']
        },
        'gmaps': {
            deps: ['jquery']
        },
        'main':{
            deps: ['jquery','gmaps']   
        }
    }
});

require(["main"], function (main) {})

But inside main.js when I try to instantiate the geocoder i got ,,undefined is not a function" error.

var geocoder = new google.maps.Geocoder();

Any ideas what could I be doing wrong?

Answer

hjuster picture hjuster · Apr 3, 2013

I've managed to sort it out with the async plugin.

A quick example is:

require.config({
    paths: {
        'async': 'lib/requirejs-plugins/src/async'
    }
});

define(['async!http://maps.google.com/maps/api/js?sensor=false'], function() {
    // Google Maps API and all its dependencies will be loaded here.
});