December 11, 2011

Coffeescript: MapsLoader class for asynchronous loading of Google Maps API

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: =>
    # 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 = "{apiKey}&callback=loadMaps"
    script.type = "text/javascript"

  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 = null

@MapsLoader = new MapsLoader()


  1. Hi Justin,

    This code is interesting and useful. What sort of licensing do you have on it? Could expand it and I use it in commercial product?

    Guy Mann

  2. Feel free to do what you will with it, for any purpose.