-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
44 lines (38 loc) · 1.44 KB
/
index.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
const API_URL = 'https://maps.googleapis.com/maps/api/js'
const CALLBACK_NAME = '__googleMapsApiOnLoadCallback'
const optionsKeys = ['channel', 'client', 'key', 'language', 'region', 'v']
let promise = null
module.exports = function (options = {}) {
promise =
promise ||
new Promise(function (resolve, reject) {
// Reject the promise after a timeout
const timeoutId = setTimeout(function () {
window[CALLBACK_NAME] = function () {} // Set the on load callback to a no-op
reject(new Error('Could not load the Google Maps API'))
}, options.timeout || 10000)
// Hook up the on load callback
window[CALLBACK_NAME] = function () {
if (timeoutId !== null) {
clearTimeout(timeoutId)
}
resolve(window.google.maps)
delete window[CALLBACK_NAME]
}
// Prepare the `script` tag to be inserted into the page
const scriptElement = document.createElement('script')
const params = [`callback=${CALLBACK_NAME}`]
optionsKeys.forEach(function (key) {
if (options[key]) {
params.push(`${key}=${options[key]}`)
}
})
if (options.libraries && options.libraries.length) {
params.push(`libraries=${options.libraries.join(',')}`)
}
scriptElement.src = `${options.apiUrl || API_URL}?${params.join('&')}`
// Insert the `script` tag
document.body.appendChild(scriptElement)
})
return promise
}