RequireJS, Google Maps, and Pathing Issues

Note: this blog post is a little convoluted because I was sort of exploring two different problems at the same time. If you are only interested in getting Google Maps to work with RequireJS, then click here.

 

I learned two lessons about RequireJS from trying to sort this one out. First, I finally figured out how to use Google Maps with RequireJS. More on that in just a minute. The other lesson I learned is about using relative paths. I made a map component and the main file is called map.js, but it uses two other .js files that reside in the same directory (map-item.js and map-collection.js). So, in require.config() I set up a path the points the the directory where all map files reside. Then, in my defines I can refer to that path and append the file I need to use as a dependency. Basic stuff, but I have to admit that RequireJS can be confusing o learn.

Anyway, back to Google Maps: I was trying to use Google Maps, which requires the 'async' module. Apparently there are different ways to get/use it. At first I was trying to load one version of it that wasn't working. So I instead loaded it via the the 'requirejs-plugins' module.

I'm installing all my libraries with bower, here's is what the package.json file looks like (just to demonstrate how I'm installing the requirejs plugins):

 

{
"name": "RequireJS Starter",
"version": "1.0.0",
"dependencies": {
"requirejs": null,
"requirejs-plugins" : null,
"jquery": null,
"backbone-amd": null,
"underscore-amd": null,
"jqueryui": "http://code.jquery.com/ui/1.10.2/jquery-ui.min.js"
}
}

 

 

 

Here is my main.js file:

 

require.config({
baseUrl: 'js',
paths: {
'jquery': '../vendor/jquery/jquery',
'underscore': '../vendor/underscore-amd/underscore',
'backbone': '../vendor/backbone-amd/backbone',
//'async': '../vendor/async/lib/async', THIS ONE DIDN'T WORK!!!
'async':'../vendor/requirejs-plugins/src/async',
'mapComponent': '../vendor/my-components/Map/js'
},
shim:{
'mapComponent':{
deps:['async']
}
}

});

require(["router"],

function(Router) {
return new Router();
}
);

 

 

Here is my app file (it's actually router.js - for this app we were playing with different ways to assemble our apps):

 

define([
'jquery',
'underscore'
'backbone',
'mapComponent'

], function($, _, Backbone, Map){

...code for router goes here

});

 

 

Here is map.js, notice how I was able to get the dependencies that reside in the same directory that map.js is in (map-item.js and map-collection.js). Also note that the last dependency is 'async....'. We don't need to reference this in any of the code in this module, so it doesn't have a corresponding parameter in the function that gets passed as the second param to define().

define([
'jquery',
'underscore',
'backbone',
'./map-item',
'./map-item-collection',
'async!http://maps.google.com/maps/api/js?sensor=false'
], function( $, _ , Backbone, MapItem, MapItemCollection){

...code for map goes here.

});