/
GoogleMapsLoader.js
113 lines (83 loc) · 2.75 KB
/
GoogleMapsLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
Wrapper library for the Google Maps JavaScript API
Attaches the API to the DOM with a script tag and returns a promise which will be resolved when the Google Maps library is loaded
Any success callbacks attached to the promise will be passed the GoogleMaps library as an argument when executed
Example:
// configure the loader
GoogleMapsLoader.key = "your_api_key";
GoogleMapsLoader.version = "3.2";
// load the google maps library and run a callback when complete
GoogleMapsLoader
.load()
.done(function(GoogleMaps) {
var map = new GoogleMaps.Map();
})
.fail(function(e, jqxhr, settings, exception) {
console.error(e);
})
*/
(function(root, factory) {
// amd support
if (typeof define === "function" && define.amd) {
define(["jquery"], factory);
// commonjs support
} else if (typeof module === "object" && exports) {
module.exports = factory(require("jquery"));
// no module support, attach module to window
} else {
root.myModule = factory(root.$);
}
})(this, function($) {
return {
// google api key, should be set when implementing the loader
key: null,
// the version of google maps library to load, defaults to 3 (was most recent major version at time of writing this loader)
version: "3",
// boolean indicating if the library has been loaded
isLoaded: false,
/**
Loads the Google Maps API
@return deferred The deferred object will be resolved when the library has loaded
*/
load: function() {
// deferred object to resolve when the library has been loaded
var deferred = $.Deferred();
// if the library has already been loaded, immediately resolve the promise
// immediately return to not load the library a second time
// if (this.isLoaded) {
// deferred.resolve(google.maps);
// return deferred.promise();
// }
// scope for closures
var that = this;
// load the google API
$.ajax({
dataType: "script",
cache: true,
url: "https://www.google.com/jsapi"
})
.done(function(data, textStatus, jqxhr) {
// check for network problem and reject the promise
if (jqxhr.readyState == 0) {
deferred.reject(jqxhr);
return;
}
// load the maps api
google.load("maps", that.version, {
other_params: "libraries=places&key="+that.key,
callback: function() {
// set that the library has been loaded
that.isLoaded = true;
// when the maps api is loaded, resolve the promise and pass the google maps object
deferred.resolve(google.maps);
}
});
})
.fail(function(e, jqxhr, settings, exception) {
deferred.reject(jqxhr);
});
// promise represents when the google maps api is loaded
return deferred.promise();
}
};
});