load-google-maps.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*!
  2. * JavaScript - loadGoogleMaps( version, apiKey, language )
  3. *
  4. * - Load Google Maps API using jQuery Deferred.
  5. * Useful if you want to only load the Google Maps API on-demand.
  6. * - Requires jQuery 1.5
  7. *
  8. * Copyright (c) 2011 Glenn Baker
  9. * Dual licensed under the MIT and GPL licenses.
  10. */
  11. /*globals window, google, jQuery*/
  12. var loadGoogleMaps = (function($) {
  13. var now = $.now(),
  14. promise;
  15. return function( version, apiKey, language ) {
  16. if( promise ) { return promise; }
  17. //Create a Deferred Object
  18. var deferred = $.Deferred(),
  19. //Declare a resolve function, pass google.maps for the done functions
  20. resolve = function () {
  21. deferred.resolve( window.google && google.maps ? google.maps : false );
  22. },
  23. //global callback name
  24. callbackName = "loadGoogleMaps_" + ( now++ ),
  25. // Default Parameters
  26. params = $.extend(
  27. {'sensor': false}
  28. , apiKey ? {"key": apiKey} : {}
  29. , language ? {"language": language} : {}
  30. );;
  31. //If google.maps exists, then Google Maps API was probably loaded with the <script> tag
  32. if( window.google && google.maps ) {
  33. resolve();
  34. //If the google.load method exists, lets load the Google Maps API in Async.
  35. } else if ( window.google && google.load ) {
  36. google.load("maps", version || 3, {"other_params": $.param(params) , "callback" : resolve});
  37. //Last, try pure jQuery Ajax technique to load the Google Maps API in Async.
  38. } else {
  39. //Ajax URL params
  40. params = $.extend( params, {
  41. 'v': version || 3,
  42. 'callback': callbackName
  43. });
  44. //Declare the global callback
  45. window[callbackName] = function( ) {
  46. resolve();
  47. //Delete callback
  48. setTimeout(function() {
  49. try{
  50. delete window[callbackName];
  51. } catch( e ) {}
  52. }, 20);
  53. };
  54. //Can't use the jXHR promise because 'script' doesn't support 'callback=?'
  55. $.ajax({
  56. dataType: 'script',
  57. data: params,
  58. url: 'http://maps.google.com/maps/api/js'
  59. });
  60. }
  61. promise = deferred.promise();
  62. return promise;
  63. };
  64. }(jQuery));