forked from google-map-react/google-map-react
/
google_map_loader.js
97 lines (79 loc) · 2.5 KB
/
google_map_loader.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
const BASE_URL = 'https://maps';
const DEFAULT_URL = `${BASE_URL}.googleapis.com`;
const API_PATH = '/maps/api/js?callback=_$_google_map_initialize_$_';
const getUrl = region => {
if (region && region.toLowerCase() === 'cn') {
return `${BASE_URL}.google.cn`;
}
return DEFAULT_URL;
};
let $script_ = null;
let loadPromise_;
let resolveCustomPromise_;
const _customPromise = new Promise(resolve => {
resolveCustomPromise_ = resolve;
});
// TODO add libraries language and other map options
export default (bootstrapURLKeys, libraries) => {
if (!$script_) {
$script_ = require('scriptjs'); // eslint-disable-line
}
// call from outside google-map-react
// will be as soon as loadPromise_ resolved
if (!bootstrapURLKeys) {
return _customPromise;
}
if (loadPromise_) {
return loadPromise_;
}
loadPromise_ = new Promise((resolve, reject) => {
if (typeof window === 'undefined') {
reject(new Error('google map cannot be loaded outside browser env'));
return;
}
if (window.google && window.google.maps) {
resolve(window.google.maps);
return;
}
if (typeof window._$_google_map_initialize_$_ !== 'undefined') {
reject(new Error('google map initialization error'));
}
window._$_google_map_initialize_$_ = () => {
delete window._$_google_map_initialize_$_;
resolve(window.google.maps);
};
if (process.env.NODE_ENV !== 'production') {
if (Object.keys(bootstrapURLKeys).indexOf('callback') > -1) {
const message = `"callback" key in bootstrapURLKeys is not allowed,
use onGoogleApiLoaded property instead`;
// eslint-disable-next-line no-console
console.error(message);
throw new Error(message);
}
}
const params = Object.keys(bootstrapURLKeys).reduce(
(r, key) => `${r}&${key}=${bootstrapURLKeys[key]}`,
''
);
const baseUrl = getUrl(bootstrapURLKeys.region);
const librariesUrl = Object.keys(libraries)
.reduce(
(libraryUrl, libraryKey) => {
if (libraries[libraryKey]) {
return `${libraryUrl}${libraryKey},`;
}
return libraryUrl;
},
'&libraries='
)
.slice(0, -1);
$script_(
`${baseUrl}${API_PATH}${params}${librariesUrl}`,
() =>
typeof window.google === 'undefined' &&
reject(new Error('google map initialization error (not loaded)'))
);
});
resolveCustomPromise_(loadPromise_);
return loadPromise_;
};