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()
A collection of handy code snippets in the languages that I use on a daily basis.
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).
Labels:
coffeescript,
google maps,
javascript,
Phonegap
Subscribe to:
Post Comments (Atom)
Hi Justin,
ReplyDeleteThis code is interesting and useful. What sort of licensing do you have on it? Could expand it and I use it in commercial product?
Thanks,
Guy Mann
Feel free to do what you will with it, for any purpose.
ReplyDelete