-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Google.js
310 lines (280 loc) · 10.5 KB
/
Google.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/**
* @module ol/source/Google
*/
import TileImage from './TileImage.js';
import ViewHint from '../ViewHint.js';
import {createXYZ, extentFromProjection} from '../tilegrid.js';
import {getBottomLeft, getTopRight} from '../extent.js';
import {toLonLat} from '../proj.js';
const createSessionUrl = 'https://tile.googleapis.com/v1/createSession';
const tileUrl = 'https://tile.googleapis.com/v1/2dtiles';
const attributionUrl = 'https://tile.googleapis.com/tile/v1/viewport';
const maxZoom = 22;
/**
* @typedef {Object} Options
* @property {string} key Google Map Tiles API key. Get yours at https://developers.google.com/maps/documentation/tile/get-api-key.
* @property {string} [mapType='roadmap'] The type of [base map](https://developers.google.com/maps/documentation/tile/session_tokens#required_fields).
* @property {string} [language='en-US'] An [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag) for information displayed on the tiles.
* @property {string} [region='US'] A [Common Locale Data Repository](https://cldr.unicode.org/) (CLDR) region identifier that represents the user location.
* @property {string} [imageFormat] The image format used for the map tiles (e.g. `'jpeg'`, or `'png'`).
* @property {string} [scale] Scale for map elements (`'scaleFactor1x'`, `'scaleFactor2x'`, or `'scaleFactor4x'`).
* @property {boolean} [highDpi=false] Use high-resolution tiles.
* @property {Array<string>} [layerTypes] The layer types added to the map (e.g. `'layerRoadmap'`, `'layerStreetview'`, or `'layerTraffic'`).
* @property {boolean} [overlay=false] Display only the `layerTypes` and not the underlying `mapType` (only works if `layerTypes` is provided).
* @property {Array<Object>} [styles] [Custom styles](https://developers.google.com/maps/documentation/tile/style-reference) applied to the map.
* @property {boolean} [attributionsCollapsible=true] Allow the attributions to be collapsed.
* @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,
* linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.
* @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.
* @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
* Higher values can increase reprojection performance, but decrease precision.
* @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
* ```js
* function(imageTile, src) {
* imageTile.getImage().src = src;
* };
* ```
* @property {boolean} [wrapX=true] Wrap the world horizontally.
* @property {number} [transition] Duration of the opacity transition for rendering.
* To disable the opacity transition, pass `transition: 0`.
* @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
* Choose whether to use tiles with a higher or lower zoom level when between integer
* zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
*/
/**
* @typedef {Object} SessionTokenRequest
* @property {string} mapType The map type.
* @property {string} language The language.
* @property {string} region The region.
* @property {string} [imageFormat] The image format.
* @property {string} [scale] The scale.
* @property {boolean} [highDpi] Use high resolution tiles.
* @property {Array<string>} [layerTypes] The layer types.
* @property {boolean} [overlay] The overlay.
* @property {Array<Object>} [styles] The styles.
*/
/**
* @typedef {Object} SessionTokenResponse
* @property {string} session The session token.
* @property {string} expiry The session token expiry (seconds since the epoch as a string).
* @property {number} tileWidth The tile width.
* @property {number} tileHeight The tile height.
* @property {string} imageFormat The image format.
*/
/**
* @classdesc
* A tile layer source that renders tiles from the Google [Map Tiles API](https://developers.google.com/maps/documentation/tile/overview).
* The constructor takes options that are passed to the request to create a session token. Refer to the
* [documentation](https://developers.google.com/maps/documentation/tile/session_tokens#required_fields)
* for additional details.
* @api
*/
class Google extends TileImage {
/**
* @param {Options} options Google Maps options.
*/
constructor(options) {
const highDpi = !!options.highDpi;
const opaque = !(options.overlay === true);
super({
attributionsCollapsible: options.attributionsCollapsible,
cacheSize: options.cacheSize,
crossOrigin: 'anonymous',
interpolate: options.interpolate,
opaque: opaque,
projection: 'EPSG:3857',
reprojectionErrorThreshold: options.reprojectionErrorThreshold,
state: 'loading',
tileLoadFunction: options.tileLoadFunction,
tilePixelRatio: highDpi ? 2 : 1,
wrapX: options.wrapX !== undefined ? options.wrapX : true,
transition: options.transition,
zDirection: options.zDirection,
});
/**
* @type {string}
* @private
*/
this.apiKey_ = options.key;
/**
* @type {Error|null}
*/
this.error_ = null;
/**
* @type {SessionTokenRequest}
*/
const sessionTokenRequest = {
mapType: options.mapType || 'roadmap',
language: options.language || 'en-US',
region: options.region || 'US',
};
if (options.imageFormat) {
sessionTokenRequest.imageFormat = options.imageFormat;
}
if (options.scale) {
sessionTokenRequest.scale = options.scale;
}
if (highDpi) {
sessionTokenRequest.highDpi = true;
}
if (options.layerTypes) {
sessionTokenRequest.layerTypes = options.layerTypes;
}
if (options.styles) {
sessionTokenRequest.styles = options.styles;
}
if (options.overlay === true) {
sessionTokenRequest.overlay = true;
}
/**
* @type {SessionTokenRequest}
* @private
*/
this.sessionTokenRequest_ = sessionTokenRequest;
/**
* @type {string}
* @private
*/
this.sessionTokenValue_;
/**
* @type {ReturnType<typeof setTimeout>}
* @private
*/
this.sessionRefreshId_;
/**
* @type {string}
* @private
*/
this.previousViewportAttribution_;
/**
* @type {string}
* @private
*/
this.previousViewportExtent_;
this.createSession_();
}
/**
* @return {Error|null} A source loading error. When the source state is `error`, use this function
* to get more information about the error. To debug a faulty configuration, you may want to use
* a listener like
* ```js
* source.on('change', () => {
* if (source.getState() === 'error') {
* console.error(source.getError());
* }
* });
* ```
*/
getError() {
return this.error_;
}
/**
* Exposed here so it can be overridden in the tests.
* @param {string} url The URL.
* @param {RequestInit} config The config.
* @return {Promise<Response>} A promise that resolves with the response.
*/
fetchSessionToken(url, config) {
return fetch(url, config);
}
/**
* Get or renew a session token for use with tile requests.
* @private
*/
async createSession_() {
const url = createSessionUrl + '?key=' + this.apiKey_;
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.sessionTokenRequest_),
};
const response = await this.fetchSessionToken(url, config);
if (!response.ok) {
try {
const body = await response.json();
this.error_ = new Error(body.error.message);
} catch {
this.error_ = new Error('Error fetching session token');
}
this.setState('error');
return;
}
/**
* @type {SessionTokenResponse}
*/
const sessionTokenResponse = await response.json();
const tilePixelRatio = this.getTilePixelRatio(1);
const tileSize = [
sessionTokenResponse.tileWidth / tilePixelRatio,
sessionTokenResponse.tileHeight / tilePixelRatio,
];
this.tileGrid = createXYZ({
extent: extentFromProjection(this.getProjection()),
maxZoom: maxZoom,
tileSize: tileSize,
});
const session = sessionTokenResponse.session;
this.sessionTokenValue_ = session;
const key = this.apiKey_;
this.tileUrlFunction = function (tileCoord, pixelRatio, projection) {
const z = tileCoord[0];
const x = tileCoord[1];
const y = tileCoord[2];
const url = `${tileUrl}/${z}/${x}/${y}?session=${session}&key=${key}`;
return url;
};
const expiry = parseInt(sessionTokenResponse.expiry, 10) * 1000;
const timeout = Math.max(expiry - Date.now() - 60 * 1000, 1);
this.sessionRefreshId_ = setTimeout(() => this.createSession_(), timeout);
this.setAttributions(this.fetchAttributions_.bind(this));
// even if the state is already ready, we want the change event
this.setState('ready');
}
/**
* @param {import('../Map.js').FrameState} frameState The frame state.
* @return {Promise<string>} The attributions.
* @private
*/
async fetchAttributions_(frameState) {
if (
frameState.viewHints[ViewHint.ANIMATING] ||
frameState.viewHints[ViewHint.INTERACTING] ||
frameState.animate
) {
return this.previousViewportAttribution_;
}
const [west, south] = toLonLat(
getBottomLeft(frameState.extent),
frameState.viewState.projection,
);
const [east, north] = toLonLat(
getTopRight(frameState.extent),
frameState.viewState.projection,
);
const tileGrid = this.getTileGrid();
const zoom = tileGrid.getZForResolution(
frameState.viewState.resolution,
this.zDirection,
);
const viewportExtent = `zoom=${zoom}&north=${north}&south=${south}&east=${east}&west=${west}`;
// check if the extent or zoom has actually changed to avoid unnecessary requests
if (this.previousViewportExtent_ == viewportExtent) {
return this.previousViewportAttribution_;
}
this.previousViewportExtent_ = viewportExtent;
const session = this.sessionTokenValue_;
const key = this.apiKey_;
const url = `${attributionUrl}?session=${session}&key=${key}&${viewportExtent}`;
this.previousViewportAttribution_ = await fetch(url)
.then((response) => response.json())
.then((json) => json.copyright);
return this.previousViewportAttribution_;
}
disposeInternal() {
clearTimeout(this.sessionRefreshId_);
super.disposeInternal();
}
}
export default Google;