Google Maps – “hello world” with RequireJS and jQuery

I’ve been looking at the Google Maps “hello world” tutorial in conjunction with HTML5 Boilerplate, RequireJS, and jQuery.

When you download and extract the boilerplate it already gives you jQuery. Given I am using RequireJS with Node (see node-reference-app) I also wanted to use on the client-side to modularize my code. It’s no big deal in itself, but I ran in to a few issues when I dropped in the Google Maps API. A search on Google soon revealed it was due to the async nature that the Google Maps API (and other Google APIs) loads its own code.

There are a number of posted solutions. The one I liked was the async plugin for RequireJS from Miller Medeiros.

Jump over to GitHub to look at the complete solution.

The basic map code is exactly as it appears in the Google Maps tutorial, however here’s a breakdown of how it fits in to HTML5 Boilerplate and RequireJS:

  • index.html – has the div for map_canvas, there is also a script tag with a data-main attribute that tells RequireJS the script to run, main.js, when the document is ready (read more here)
  • style.css – specifies the width and height for map_canvas
  • main.js – this is where the real work begins, we grab map_canvas from the DOM with the help of jQuery and call addMapToCanvas() on the google module
  • google.js – this is the heart of the solution to the async problem, if you look at the top you will see the URL is prefixed with async!, which causes the async plugin to be called

Note: to use the example make sure to obtain your own api key and add it to the URL in google.js where it says YOUR_KEY.

Advertisements

2 thoughts on “Google Maps – “hello world” with RequireJS and jQuery

  1. Loading JavaScript in order of dependencies with Require.js | appsgoogleplus.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s