@math.gl/web-mercator 3.5.6 → 3.6.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/assert.d.ts +2 -0
  2. package/dist/assert.d.ts.map +1 -0
  3. package/dist/assert.js +8 -0
  4. package/dist/es5/assert.js.map +1 -1
  5. package/dist/es5/fit-bounds.js +33 -37
  6. package/dist/es5/fit-bounds.js.map +1 -1
  7. package/dist/es5/fly-to-viewport.js +23 -16
  8. package/dist/es5/fly-to-viewport.js.map +1 -1
  9. package/dist/es5/get-bounds.js +1 -1
  10. package/dist/es5/get-bounds.js.map +1 -1
  11. package/dist/es5/index.js +6 -0
  12. package/dist/es5/index.js.map +1 -1
  13. package/dist/es5/math-utils.js +8 -9
  14. package/dist/es5/math-utils.js.map +1 -1
  15. package/dist/es5/normalize-viewport-props.js +10 -10
  16. package/dist/es5/normalize-viewport-props.js.map +1 -1
  17. package/dist/es5/web-mercator-utils.js +47 -61
  18. package/dist/es5/web-mercator-utils.js.map +1 -1
  19. package/dist/es5/web-mercator-viewport.js +69 -51
  20. package/dist/es5/web-mercator-viewport.js.map +1 -1
  21. package/dist/esm/assert.js.map +1 -1
  22. package/dist/esm/fit-bounds.js +29 -34
  23. package/dist/esm/fit-bounds.js.map +1 -1
  24. package/dist/esm/fly-to-viewport.js +13 -9
  25. package/dist/esm/fly-to-viewport.js.map +1 -1
  26. package/dist/esm/get-bounds.js +1 -1
  27. package/dist/esm/get-bounds.js.map +1 -1
  28. package/dist/esm/index.js +1 -1
  29. package/dist/esm/index.js.map +1 -1
  30. package/dist/esm/math-utils.js +6 -3
  31. package/dist/esm/math-utils.js.map +1 -1
  32. package/dist/esm/normalize-viewport-props.js +13 -9
  33. package/dist/esm/normalize-viewport-props.js.map +1 -1
  34. package/dist/esm/web-mercator-utils.js +47 -52
  35. package/dist/esm/web-mercator-utils.js.map +1 -1
  36. package/dist/esm/web-mercator-viewport.js +76 -34
  37. package/dist/esm/web-mercator-viewport.js.map +1 -1
  38. package/dist/fit-bounds.d.ts +50 -0
  39. package/dist/fit-bounds.d.ts.map +1 -0
  40. package/dist/fit-bounds.js +63 -0
  41. package/dist/fly-to-viewport.d.ts +19 -0
  42. package/dist/fly-to-viewport.d.ts.map +1 -0
  43. package/dist/fly-to-viewport.js +87 -0
  44. package/dist/get-bounds.d.ts +3 -0
  45. package/dist/get-bounds.d.ts.map +1 -0
  46. package/dist/get-bounds.js +51 -0
  47. package/dist/index.d.ts +11 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +8 -0
  50. package/dist/math-utils.d.ts +7 -0
  51. package/dist/math-utils.d.ts.map +1 -0
  52. package/dist/math-utils.js +26 -0
  53. package/dist/normalize-viewport-props.d.ts +16 -0
  54. package/dist/normalize-viewport-props.d.ts.map +1 -0
  55. package/dist/normalize-viewport-props.js +41 -0
  56. package/dist/{es5/web-mercator-utils.d.ts → web-mercator-utils.d.ts} +78 -94
  57. package/dist/web-mercator-utils.d.ts.map +1 -0
  58. package/dist/web-mercator-utils.js +290 -0
  59. package/dist/web-mercator-viewport.d.ts +182 -0
  60. package/dist/web-mercator-viewport.d.ts.map +1 -0
  61. package/dist/web-mercator-viewport.js +281 -0
  62. package/package.json +4 -4
  63. package/src/{assert.js → assert.ts} +1 -1
  64. package/src/fit-bounds.ts +127 -0
  65. package/src/{fly-to-viewport.js → fly-to-viewport.ts} +52 -14
  66. package/src/{get-bounds.js → get-bounds.ts} +7 -5
  67. package/src/{index.js → index.ts} +5 -0
  68. package/src/math-utils.ts +32 -0
  69. package/src/{normalize-viewport-props.js → normalize-viewport-props.ts} +19 -10
  70. package/src/{web-mercator-utils.js → web-mercator-utils.ts} +186 -76
  71. package/src/web-mercator-viewport.ts +415 -0
  72. package/dist/es5/fit-bounds.d.ts +0 -64
  73. package/dist/es5/fly-to-viewport.d.ts +0 -31
  74. package/dist/es5/get-bounds.d.ts +0 -3
  75. package/dist/es5/index.d.ts +0 -23
  76. package/dist/es5/normalize-viewport-props.d.ts +0 -16
  77. package/dist/es5/web-mercator-viewport.d.ts +0 -187
  78. package/dist/esm/fit-bounds.d.ts +0 -64
  79. package/dist/esm/fly-to-viewport.d.ts +0 -31
  80. package/dist/esm/get-bounds.d.ts +0 -3
  81. package/dist/esm/index.d.ts +0 -23
  82. package/dist/esm/normalize-viewport-props.d.ts +0 -16
  83. package/dist/esm/web-mercator-utils.d.ts +0 -189
  84. package/dist/esm/web-mercator-viewport.d.ts +0 -187
  85. package/src/fit-bounds.d.ts +0 -64
  86. package/src/fit-bounds.js +0 -84
  87. package/src/fly-to-viewport.d.ts +0 -31
  88. package/src/get-bounds.d.ts +0 -3
  89. package/src/index.d.ts +0 -23
  90. package/src/math-utils.js +0 -28
  91. package/src/normalize-viewport-props.d.ts +0 -16
  92. package/src/web-mercator-utils.d.ts +0 -189
  93. package/src/web-mercator-viewport.d.ts +0 -187
  94. package/src/web-mercator-viewport.js +0 -262
@@ -0,0 +1,281 @@
1
+ // View and Projection Matrix calculations for mapbox-js style map view properties
2
+ import { createMat4 } from './math-utils';
3
+ import { zoomToScale, pixelsToWorld, lngLatToWorld, worldToLngLat, worldToPixels, altitudeToFovy, fovyToAltitude, DEFAULT_ALTITUDE, getProjectionMatrix, getDistanceScales, getViewMatrix } from './web-mercator-utils';
4
+ import fitBounds from './fit-bounds';
5
+ import getBounds from './get-bounds';
6
+ import * as mat4 from 'gl-matrix/mat4';
7
+ import * as vec2 from 'gl-matrix/vec2';
8
+ import * as vec3 from 'gl-matrix/vec3';
9
+ /**
10
+ * The WebMercatorViewport class creates
11
+ * - view/projection matrices
12
+ * - "uniform values" (for shaders) from mercator params
13
+ *
14
+ * Note: Instances are immutable in the sense that they only have accessors.
15
+ * A new viewport instance should be created if any parameters have changed.
16
+ */
17
+ export default class WebMercatorViewport {
18
+ /**
19
+ * @classdesc
20
+ * Creates view/projection matrices from mercator params
21
+ * Note: The Viewport is immutable in the sense that it only has accessors.
22
+ * A new viewport instance should be created if any parameters have changed.
23
+ */
24
+ // eslint-disable-next-line max-statements
25
+ constructor(props = { width: 1, height: 1 }) {
26
+ let {
27
+ // Map state
28
+ width, height, altitude = null, fovy = null } = props;
29
+ const { latitude = 0, longitude = 0, zoom = 0, pitch = 0, bearing = 0, position = null, nearZMultiplier = 0.02, farZMultiplier = 1.01 } = props;
30
+ // Silently allow apps to send in 0,0 to facilitate isomorphic render etc
31
+ width = width || 1;
32
+ height = height || 1;
33
+ // `fovy` & `altitude` are independent parameters, one for the
34
+ // projection and the latter for the view matrix. In the past,
35
+ // the `fovy` was always derived from the `altitude`
36
+ if (fovy === null && altitude === null) {
37
+ altitude = DEFAULT_ALTITUDE;
38
+ fovy = altitudeToFovy(altitude);
39
+ }
40
+ else if (fovy === null) {
41
+ fovy = altitudeToFovy(altitude);
42
+ }
43
+ else if (altitude === null) {
44
+ altitude = fovyToAltitude(fovy);
45
+ }
46
+ const scale = zoomToScale(zoom);
47
+ // Altitude - prevent division by 0
48
+ // TODO - just throw an Error instead?
49
+ altitude = Math.max(0.75, altitude);
50
+ const distanceScales = getDistanceScales({ longitude, latitude });
51
+ const center = lngLatToWorld([longitude, latitude]);
52
+ center.push(0);
53
+ if (position) {
54
+ vec3.add(center, center, vec3.mul([], position, distanceScales.unitsPerMeter));
55
+ }
56
+ this.projectionMatrix = getProjectionMatrix({
57
+ width,
58
+ height,
59
+ pitch,
60
+ fovy,
61
+ nearZMultiplier,
62
+ farZMultiplier
63
+ });
64
+ this.viewMatrix = getViewMatrix({
65
+ height,
66
+ scale,
67
+ center,
68
+ pitch,
69
+ bearing,
70
+ altitude
71
+ });
72
+ // Save parameters
73
+ this.width = width;
74
+ this.height = height;
75
+ this.scale = scale;
76
+ this.latitude = latitude;
77
+ this.longitude = longitude;
78
+ this.zoom = zoom;
79
+ this.pitch = pitch;
80
+ this.bearing = bearing;
81
+ this.altitude = altitude;
82
+ this.fovy = fovy;
83
+ this.center = center;
84
+ this.meterOffset = position || [0, 0, 0];
85
+ this.distanceScales = distanceScales;
86
+ this._initMatrices();
87
+ // Bind methods for easy access
88
+ this.equals = this.equals.bind(this);
89
+ this.project = this.project.bind(this);
90
+ this.unproject = this.unproject.bind(this);
91
+ this.projectPosition = this.projectPosition.bind(this);
92
+ this.unprojectPosition = this.unprojectPosition.bind(this);
93
+ Object.freeze(this);
94
+ }
95
+ _initMatrices() {
96
+ const { width, height, projectionMatrix, viewMatrix } = this;
97
+ // Note: As usual, matrix operations should be applied in "reverse" order
98
+ // since vectors will be multiplied in from the right during transformation
99
+ const vpm = createMat4();
100
+ mat4.multiply(vpm, vpm, projectionMatrix);
101
+ mat4.multiply(vpm, vpm, viewMatrix);
102
+ this.viewProjectionMatrix = vpm;
103
+ // Calculate matrices and scales needed for projection
104
+ /**
105
+ * Builds matrices that converts preprojected lngLats to screen pixels
106
+ * and vice versa.
107
+ * Note: Currently returns bottom-left coordinates!
108
+ * Note: Starts with the GL projection matrix and adds steps to the
109
+ * scale and translate that matrix onto the window.
110
+ * Note: WebGL controls clip space to screen projection with gl.viewport
111
+ * and does not need this step.
112
+ */
113
+ const m = createMat4();
114
+ // matrix for conversion from location to screen coordinates
115
+ mat4.scale(m, m, [width / 2, -height / 2, 1]);
116
+ mat4.translate(m, m, [1, -1, 0]);
117
+ mat4.multiply(m, m, vpm);
118
+ const mInverse = mat4.invert(createMat4(), m);
119
+ if (!mInverse) {
120
+ throw new Error('Pixel project matrix not invertible');
121
+ }
122
+ this.pixelProjectionMatrix = m;
123
+ this.pixelUnprojectionMatrix = mInverse;
124
+ }
125
+ /** Two viewports are equal if width and height are identical, and if
126
+ * their view and projection matrices are (approximately) equal.
127
+ */
128
+ equals(viewport) {
129
+ if (!(viewport instanceof WebMercatorViewport)) {
130
+ return false;
131
+ }
132
+ return (viewport.width === this.width &&
133
+ viewport.height === this.height &&
134
+ mat4.equals(viewport.projectionMatrix, this.projectionMatrix) &&
135
+ mat4.equals(viewport.viewMatrix, this.viewMatrix));
136
+ }
137
+ /**
138
+ * Projects xyz (possibly latitude and longitude) to pixel coordinates in window
139
+ * using viewport projection parameters
140
+ * - [longitude, latitude] to [x, y]
141
+ * - [longitude, latitude, Z] => [x, y, z]
142
+ * Note: By default, returns top-left coordinates for canvas/SVG type render
143
+ *
144
+ * @param lngLatZ - [lng, lat] or [lng, lat, Z]
145
+ * @param options - options
146
+ * @param options.topLeft=true - Whether projected coords are top left
147
+ * @return - screen coordinates [x, y] or [x, y, z], z as pixel depth
148
+ */
149
+ project(lngLatZ, options = {}) {
150
+ const { topLeft = true } = options;
151
+ const worldPosition = this.projectPosition(lngLatZ);
152
+ const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);
153
+ const [x, y] = coord;
154
+ const y2 = topLeft ? y : this.height - y;
155
+ return lngLatZ.length === 2 ? [x, y2] : [x, y2, coord[2]];
156
+ }
157
+ /**
158
+ * Unproject pixel coordinates on screen onto world coordinates, possibly `[lon, lat]` on map.
159
+ *
160
+ * - [x, y] => [lng, lat]
161
+ * - [x, y, z] => [lng, lat, Z]
162
+ *
163
+ * @param xyz - screen coordinates, z as pixel depth
164
+ * @param options - options
165
+ * @param options.topLeft=true - Whether projected coords are top left
166
+ * @param options.targetZ=0 - If pixel depth is unknown, targetZ is used as
167
+ * the elevation plane to unproject onto
168
+ * @return - [lng, lat, Z] or [X, Y, Z]
169
+ */
170
+ unproject(xyz, options = {}) {
171
+ const { topLeft = true, targetZ = undefined } = options;
172
+ const [x, y, z] = xyz;
173
+ const y2 = topLeft ? y : this.height - y;
174
+ const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];
175
+ const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);
176
+ const [X, Y, Z] = this.unprojectPosition(coord);
177
+ if (Number.isFinite(z)) {
178
+ return [X, Y, Z];
179
+ }
180
+ return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y];
181
+ }
182
+ // NON_LINEAR PROJECTION HOOKS
183
+ // Used for web meractor projection
184
+ projectPosition(xyz) {
185
+ const [X, Y] = lngLatToWorld(xyz);
186
+ const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];
187
+ return [X, Y, Z];
188
+ }
189
+ unprojectPosition(xyz) {
190
+ const [X, Y] = worldToLngLat(xyz);
191
+ const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];
192
+ return [X, Y, Z];
193
+ }
194
+ /**
195
+ * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
196
+ * Performs the nonlinear part of the web mercator projection.
197
+ * Remaining projection is done with 4x4 matrices which also handles
198
+ * perspective.
199
+ *
200
+ * @param lngLat - [lng, lat] coordinates
201
+ * Specifies a point on the sphere to project onto the map.
202
+ * @return [x,y] coordinates.
203
+ */
204
+ projectFlat(lngLat) {
205
+ return lngLatToWorld(lngLat);
206
+ }
207
+ /**
208
+ * Unproject world point [x,y] on map onto {lat, lon} on sphere
209
+ *
210
+ * @param xy - array with [x,y] members
211
+ * representing point on projected map plane
212
+ * @return - array with [lat,lon] of point on sphere.
213
+ * Has toArray method if you need a GeoJSON Array.
214
+ * Per cartographic tradition, lat and lon are specified as degrees.
215
+ */
216
+ unprojectFlat(xy) {
217
+ return worldToLngLat(xy);
218
+ }
219
+ /**
220
+ * Get the map center that place a given [lng, lat] coordinate at screen point [x, y]
221
+ * @param opt
222
+ * @param opt.lngLat - [lng,lat] coordinates
223
+ * Specifies a point on the sphere.
224
+ * @param opt.pos - [x,y] coordinates
225
+ * Specifies a point on the screen.
226
+ * @return [lng,lat] new map center.
227
+ */
228
+ getMapCenterByLngLatPosition({ lngLat, pos }) {
229
+ const fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix);
230
+ const toLocation = lngLatToWorld(lngLat);
231
+ const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));
232
+ const newCenter = vec2.add([], this.center, translate);
233
+ return worldToLngLat(newCenter);
234
+ }
235
+ /**
236
+ * Returns a new viewport that fit around the given rectangle.
237
+ * Only supports non-perspective mode.
238
+ * @param bounds - [[lon, lat], [lon, lat]]
239
+ * @param [options]
240
+ * @param [options.padding] - The amount of padding in pixels to add to the given bounds.
241
+ * @param [options.offset] - The center of the given bounds relative to the map's center,
242
+ * [x, y] measured in pixels.
243
+ * @returns {WebMercatorViewport}
244
+ */
245
+ fitBounds(bounds, options = {}) {
246
+ const { width, height } = this;
247
+ const { longitude, latitude, zoom } = fitBounds(Object.assign({ width, height, bounds }, options));
248
+ return new WebMercatorViewport({ width, height, longitude, latitude, zoom });
249
+ }
250
+ /**
251
+ * Returns the bounding box of the viewport.
252
+ * @param [options]
253
+ * @param [options.z] - The altitude at which the bounds should be calculated.
254
+ * @returns {Array} bounds - [[lon, lat], [lon, lat]]
255
+ */
256
+ getBounds(options) {
257
+ const corners = this.getBoundingRegion(options);
258
+ const west = Math.min(...corners.map((p) => p[0]));
259
+ const east = Math.max(...corners.map((p) => p[0]));
260
+ const south = Math.min(...corners.map((p) => p[1]));
261
+ const north = Math.max(...corners.map((p) => p[1]));
262
+ return [
263
+ [west, south],
264
+ [east, north]
265
+ ];
266
+ }
267
+ /**
268
+ * Returns the bounding box of the viewport.
269
+ * @param [options]
270
+ * @param [options.z] - The altitude at which the bounds should be calculated.
271
+ * @returns {Array} an array of 4 points that define the visible region
272
+ */
273
+ getBoundingRegion(options = {}) {
274
+ return getBounds(this, options.z || 0);
275
+ }
276
+ // DEPRECATED
277
+ /** @deprecated Legacy method name */
278
+ getLocationAtPoint({ lngLat, pos }) {
279
+ return this.getMapCenterByLngLatPosition({ lngLat, pos });
280
+ }
281
+ }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Utilities for perspective-enabled Web Mercator projections",
4
4
  "author": "Uber Technologies, Inc.",
5
5
  "license": "MIT",
6
- "version": "3.5.6",
6
+ "version": "3.6.0-alpha.2",
7
7
  "keywords": [
8
8
  "webgl",
9
9
  "javascript",
@@ -18,7 +18,7 @@
18
18
  "type": "git",
19
19
  "url": "https://github.com/uber-web/math.gl.git"
20
20
  },
21
- "types": "src/index.d.ts",
21
+ "types": "dist/index.d.ts",
22
22
  "main": "dist/es5/index.js",
23
23
  "module": "dist/esm/index.js",
24
24
  "files": [
@@ -27,11 +27,11 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "@babel/runtime": "^7.12.0",
30
- "gl-matrix": "~3.3.0"
30
+ "gl-matrix": "^3.4.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "mapbox-gl": "^1.0.0",
34
34
  "mock-browser": "^0.92.14"
35
35
  },
36
- "gitHead": "0e69c70ff2e6373fed84d303cbf8198a6972944f"
36
+ "gitHead": "ea7dc265c98b68af56218302d1d42b7d65f74ccb"
37
37
  }
@@ -1,7 +1,7 @@
1
1
  // Replacement for the external assert method to reduce bundle size
2
2
  // Note: We don't use the second "message" argument in calling code,
3
3
  // so no need to support it here
4
- export default function assert(condition, message) {
4
+ export default function assert(condition: unknown, message?: string): void {
5
5
  if (!condition) {
6
6
  throw new Error(message || '@math.gl/web-mercator: assertion failed.');
7
7
  }
@@ -0,0 +1,127 @@
1
+ import assert from './assert';
2
+ import {log2, clamp} from './math-utils';
3
+ import {MAX_LATITUDE, lngLatToWorld, worldToLngLat} from './web-mercator-utils';
4
+
5
+ /**
6
+ * Options for fitBounds
7
+ * @param width - viewport width
8
+ * @param height - viewport height
9
+ * @param bounds - [[lon, lat], [lon, lat]]
10
+ * @param minExtent - The width/height of the bounded area will never be smaller than this
11
+ * @param padding - The amount of padding in pixels
12
+ * to add to the given bounds. Can also be an object with top, bottom, left and right
13
+ * properties defining the padding.
14
+ * @param options.offset= - The center of the given bounds relative to the map's center,
15
+ */
16
+ export type FitBoundsOptions = {
17
+ width: number;
18
+ height: number;
19
+ bounds: [[number, number], [number, number]];
20
+ minExtent?: number; // 0.01 would be about 1000 meters (degree is ~110KM)
21
+ maxZoom?: number; // ~x4,000,000 => About 10 meter extents
22
+ // options
23
+ padding?: number | Padding;
24
+ offset?: number[];
25
+ };
26
+
27
+ /**
28
+ * An object describing the padding to add to the bounds.
29
+ * @property top - Padding from top in pixels to add to the given bounds
30
+ * @property bottom - Padding from bottom in pixels to add to the given bounds
31
+ * @property left - Padding from left in pixels to add to the given bounds
32
+ * @property right - Padding from right in pixels to add to the given bounds
33
+ */
34
+ export type Padding = {
35
+ top: number;
36
+ bottom: number;
37
+ left: number;
38
+ right: number;
39
+ };
40
+
41
+ type ViewportProps = {
42
+ longitude: number;
43
+ latitude: number;
44
+ zoom: number;
45
+ };
46
+
47
+ /**
48
+ * Returns map settings {latitude, longitude, zoom}
49
+ * that will contain the provided corners within the provided width.
50
+ *
51
+ * > _Note: Only supports non-perspective mode._
52
+ *
53
+ * @param options fit bounds parameters
54
+ * @returns - latitude, longitude and zoom
55
+ */
56
+ export default function fitBounds(options: FitBoundsOptions): ViewportProps {
57
+ const {
58
+ width,
59
+ height,
60
+ bounds,
61
+ minExtent = 0, // 0.01 would be about 1000 meters (degree is ~110KM)
62
+ maxZoom = 24, // ~x4,000,000 => About 10 meter extents
63
+ offset = [0, 0]
64
+ } = options;
65
+
66
+ const [[west, south], [east, north]] = bounds;
67
+ const padding = getPaddingObject(options.padding);
68
+
69
+ const nw = lngLatToWorld([west, clamp(north, -MAX_LATITUDE, MAX_LATITUDE)]);
70
+ const se = lngLatToWorld([east, clamp(south, -MAX_LATITUDE, MAX_LATITUDE)]);
71
+
72
+ // width/height on the Web Mercator plane
73
+ const size = [
74
+ Math.max(Math.abs(se[0] - nw[0]), minExtent),
75
+ Math.max(Math.abs(se[1] - nw[1]), minExtent)
76
+ ];
77
+
78
+ const targetSize = [
79
+ width - padding.left - padding.right - Math.abs(offset[0]) * 2,
80
+ height - padding.top - padding.bottom - Math.abs(offset[1]) * 2
81
+ ];
82
+
83
+ assert(targetSize[0] > 0 && targetSize[1] > 0);
84
+
85
+ // scale = screen pixels per unit on the Web Mercator plane
86
+ const scaleX = targetSize[0] / size[0];
87
+ const scaleY = targetSize[1] / size[1];
88
+
89
+ // Find how much we need to shift the center
90
+ const offsetX = (padding.right - padding.left) / 2 / scaleX;
91
+ const offsetY = (padding.bottom - padding.top) / 2 / scaleY;
92
+
93
+ const center = [(se[0] + nw[0]) / 2 + offsetX, (se[1] + nw[1]) / 2 + offsetY];
94
+
95
+ const centerLngLat = worldToLngLat(center);
96
+ const zoom = Math.min(maxZoom, log2(Math.abs(Math.min(scaleX, scaleY))));
97
+
98
+ assert(Number.isFinite(zoom));
99
+
100
+ return {
101
+ longitude: centerLngLat[0],
102
+ latitude: centerLngLat[1],
103
+ zoom
104
+ };
105
+ }
106
+
107
+ // Helpers
108
+ function getPaddingObject(padding: number | Padding = 0): Padding {
109
+ if (typeof padding === 'number') {
110
+ return {
111
+ top: padding,
112
+ bottom: padding,
113
+ left: padding,
114
+ right: padding
115
+ };
116
+ }
117
+
118
+ // Make sure all the required properties are set
119
+ assert(
120
+ Number.isFinite(padding.top) &&
121
+ Number.isFinite(padding.bottom) &&
122
+ Number.isFinite(padding.left) &&
123
+ Number.isFinite(padding.right)
124
+ );
125
+
126
+ return padding;
127
+ }
@@ -2,37 +2,55 @@ import {lerp} from './math-utils';
2
2
  import {scaleToZoom, zoomToScale, lngLatToWorld, worldToLngLat} from './web-mercator-utils';
3
3
  import * as vec2 from 'gl-matrix/vec2';
4
4
 
5
+ import type {ViewportProps} from './normalize-viewport-props';
6
+
5
7
  const EPSILON = 0.01;
6
- const VIEWPORT_TRANSITION_PROPS = ['longitude', 'latitude', 'zoom'];
8
+ const VIEWPORT_TRANSITION_PROPS = ['longitude', 'latitude', 'zoom'] as const;
7
9
  const DEFAULT_OPTS = {
8
10
  curve: 1.414,
9
11
  speed: 1.2
10
12
  // screenSpeed and maxDuration are used only if specified
11
13
  };
12
14
 
15
+ export type FlytoTransitionOptions = {
16
+ curve?: number;
17
+ speed?: number;
18
+ screenSpeed?: number;
19
+ maxDuration?: number;
20
+ };
21
+
13
22
  /**
14
23
  * mapbox-gl-js flyTo : https://www.mapbox.com/mapbox-gl-js/api/#map#flyto.
15
24
  * It implements “Smooth and efficient zooming and panning.” algorithm by
16
25
  * "Jarke J. van Wijk and Wim A.A. Nuij"
17
26
  */
18
- export default function flyToViewport(startProps, endProps, t, opts = {}) {
27
+ export default function flyToViewport(
28
+ startProps: ViewportProps,
29
+ endProps: ViewportProps,
30
+ t: number,
31
+ options?: FlytoTransitionOptions
32
+ ): {
33
+ longitude: number;
34
+ latitude: number;
35
+ zoom: number;
36
+ } {
19
37
  // Equations from above paper are referred where needed.
20
38
 
21
- const viewport = {};
22
-
23
39
  const {startZoom, startCenterXY, uDelta, w0, u1, S, rho, rho2, r0} = getFlyToTransitionParams(
24
40
  startProps,
25
41
  endProps,
26
- opts
42
+ options
27
43
  );
28
44
 
29
45
  // If change in center is too small, do linear interpolaiton.
30
46
  if (u1 < EPSILON) {
47
+ const viewport = {};
31
48
  for (const key of VIEWPORT_TRANSITION_PROPS) {
32
49
  const startValue = startProps[key];
33
50
  const endValue = endProps[key];
34
51
  viewport[key] = lerp(startValue, endValue, t);
35
52
  }
53
+ // @ts-expect-error
36
54
  return viewport;
37
55
  }
38
56
 
@@ -48,19 +66,24 @@ export default function flyToViewport(startProps, endProps, t, opts = {}) {
48
66
  vec2.add(newCenterWorld, newCenterWorld, startCenterXY);
49
67
 
50
68
  const newCenter = worldToLngLat(newCenterWorld);
51
- viewport.longitude = newCenter[0];
52
- viewport.latitude = newCenter[1];
53
- viewport.zoom = newZoom;
54
- return viewport;
69
+ return {
70
+ longitude: newCenter[0],
71
+ latitude: newCenter[1],
72
+ zoom: newZoom
73
+ };
55
74
  }
56
75
 
57
76
  // returns transition duration in milliseconds
58
- export function getFlyToDuration(startProps, endProps, opts = {}) {
59
- opts = Object.assign({}, DEFAULT_OPTS, opts);
77
+ export function getFlyToDuration(
78
+ startProps: ViewportProps,
79
+ endProps: ViewportProps,
80
+ options?: FlytoTransitionOptions
81
+ ): number {
82
+ const opts = {...DEFAULT_OPTS, ...options};
60
83
  const {screenSpeed, speed, maxDuration} = opts;
61
84
  const {S, rho} = getFlyToTransitionParams(startProps, endProps, opts);
62
85
  const length = 1000 * S;
63
- let duration;
86
+ let duration: number;
64
87
  if (Number.isFinite(screenSpeed)) {
65
88
  duration = length / (screenSpeed / rho);
66
89
  } else {
@@ -73,7 +96,22 @@ export function getFlyToDuration(startProps, endProps, opts = {}) {
73
96
  // Private Methods
74
97
 
75
98
  // Calculate all parameters that are static for given startProps and endProps
76
- function getFlyToTransitionParams(startProps, endProps, opts) {
99
+ function getFlyToTransitionParams(
100
+ startProps: ViewportProps,
101
+ endProps: ViewportProps,
102
+ opts: FlytoTransitionOptions
103
+ ): {
104
+ startZoom: number;
105
+ startCenterXY: number[];
106
+ uDelta: number[];
107
+ w0: number;
108
+ u1: number;
109
+ S: number;
110
+ rho: number;
111
+ rho2: number;
112
+ r0: number;
113
+ r1: number;
114
+ } {
77
115
  opts = Object.assign({}, DEFAULT_OPTS, opts);
78
116
  const rho = opts.curve;
79
117
  const startZoom = startProps.zoom;
@@ -85,7 +123,7 @@ function getFlyToTransitionParams(startProps, endProps, opts) {
85
123
 
86
124
  const startCenterXY = lngLatToWorld(startCenter);
87
125
  const endCenterXY = lngLatToWorld(endCenter);
88
- const uDelta = vec2.sub([], endCenterXY, startCenterXY);
126
+ const uDelta = vec2.sub([] as number[], endCenterXY, startCenterXY);
89
127
 
90
128
  const w0 = Math.max(startProps.width, startProps.height);
91
129
  const w1 = w0 / scale;
@@ -1,6 +1,7 @@
1
1
  import {worldToLngLat} from './web-mercator-utils';
2
2
  import * as vec2 from 'gl-matrix/vec2';
3
3
  import {transformVector} from './math-utils';
4
+ import type WebMercatorViewport from './web-mercator-viewport';
4
5
 
5
6
  const DEGREES_TO_RADIANS = Math.PI / 180;
6
7
 
@@ -9,13 +10,14 @@ const DEGREES_TO_RADIANS = Math.PI / 180;
9
10
  * @param {WebMercatorViewport} viewport
10
11
  * @param {Number} z - elevation in meters
11
12
  */
12
- export default function getBounds(viewport, z = 0) {
13
+ export default function getBounds(viewport: WebMercatorViewport, z: number = 0): number[][] {
14
+ // eslint-disable-next-line @typescript-eslint/unbound-method
13
15
  const {width, height, unproject} = viewport;
14
16
  const unprojectOps = {targetZ: z};
15
17
  const bottomLeft = unproject([0, height], unprojectOps);
16
18
  const bottomRight = unproject([width, height], unprojectOps);
17
- let topLeft;
18
- let topRight;
19
+ let topLeft: number[];
20
+ let topRight: number[];
19
21
 
20
22
  const halfFov = viewport.fovy
21
23
  ? 0.5 * viewport.fovy * DEGREES_TO_RADIANS
@@ -41,7 +43,7 @@ export default function getBounds(viewport, z = 0) {
41
43
  * @param {Number} x - projected x in screen space
42
44
  * @param {Number} targetZ - the elevation of the point in meters
43
45
  */
44
- function unprojectOnFarPlane(viewport, x, targetZ) {
46
+ function unprojectOnFarPlane(viewport: WebMercatorViewport, x: number, targetZ: number): number[] {
45
47
  const {pixelUnprojectionMatrix} = viewport;
46
48
  const coord0 = transformVector(pixelUnprojectionMatrix, [x, 0, 1, 1]);
47
49
  const coord1 = transformVector(pixelUnprojectionMatrix, [x, viewport.height, 1, 1]);
@@ -51,6 +53,6 @@ function unprojectOnFarPlane(viewport, x, targetZ) {
51
53
  const coord = vec2.lerp([], coord0, coord1, t);
52
54
 
53
55
  const result = worldToLngLat(coord);
54
- result[2] = targetZ;
56
+ result.push(targetZ);
55
57
  return result;
56
58
  }
@@ -8,6 +8,7 @@ export {default as normalizeViewportProps} from './normalize-viewport-props';
8
8
  export {default as flyToViewport, getFlyToDuration} from './fly-to-viewport';
9
9
 
10
10
  export {
11
+ MAX_LATITUDE,
11
12
  lngLatToWorld,
12
13
  worldToLngLat,
13
14
  worldToPixels,
@@ -23,3 +24,7 @@ export {
23
24
  getProjectionMatrix,
24
25
  getProjectionParameters
25
26
  } from './web-mercator-utils';
27
+
28
+ /** Types */
29
+ export type {FitBoundsOptions} from './fit-bounds';
30
+ export type {DistanceScales} from './web-mercator-utils';
@@ -0,0 +1,32 @@
1
+ import {transformMat4, scale} from 'gl-matrix/vec4';
2
+
3
+ // Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()
4
+ export function createMat4(): number[] {
5
+ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
6
+ }
7
+
8
+ // Transforms a vec4 with a projection matrix
9
+ export function transformVector(matrix: number[], vector: number[]): number[] {
10
+ const result = transformMat4([] as number[], vector, matrix);
11
+ scale(result, result, 1 / result[3]);
12
+ return result;
13
+ }
14
+
15
+ export function mod(value: number, divisor: number): number {
16
+ const modulus = value % divisor;
17
+ return modulus < 0 ? divisor + modulus : modulus;
18
+ }
19
+
20
+ export function lerp(start: number, end: number, step: number): number {
21
+ return step * end + (1 - step) * start;
22
+ }
23
+
24
+ export function clamp(x: number, min: number, max: number): number {
25
+ return x < min ? min : x > max ? max : x;
26
+ }
27
+
28
+ function ieLog2(x: number): number {
29
+ return Math.log(x) * Math.LOG2E;
30
+ }
31
+ // Handle missing log2 in IE 11
32
+ export const log2 = Math.log2 || ieLog2;