I'm using CoffeeScript for my current project, and we needed a way to load the Google Maps API when a user hits a particular view. This static class is auto-initialized, and all you need to call is:
MapsLoader.load(callbackFunction,true). If the API has already loaded, it will invoke your callback immediately. Make sure to pass the appropriate boolean if the user is on a mobile device (true), or a desktop browser (false).
class MapsLoader
constructor: ->
load: (successCallback,isMobileDevice) ->
@isMobileDevice = isMobileDevice
@successCallback = successCallback
if @hasLoaded != true
@loadGoogle()
else
@mapsLoaded()
loadGoogle: =>
# reference google loader callback to local method - clean up after callback
window.loadMaps = @loadMaps
apiKey = "-----your-api-key-here-----"
script = document.createElement("script")
script.src = "https://www.google.com/jsapi?key=#{apiKey}&callback=loadMaps"
script.type = "text/javascript"
document.getElementsByTagName("head")[0].appendChild(script)
loadMaps: =>
otherParams = if @isMobileDevice then "sensor=true" else "sensor=false"
google.load("maps", "3", {other_params: otherParams, "callback" : @mapsLoaded});
mapsLoaded: =>
@hasLoaded = true
window.loadMaps = null
if @successCallback
@successCallback()
@successCallback = null
@MapsLoader = new MapsLoader()