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

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 (91) 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 +40 -50
  6. package/dist/es5/fit-bounds.js.map +1 -1
  7. package/dist/es5/fly-to-viewport.js +82 -98
  8. package/dist/es5/fly-to-viewport.js.map +1 -1
  9. package/dist/es5/get-bounds.js +25 -24
  10. package/dist/es5/get-bounds.js.map +1 -1
  11. package/dist/es5/index.js +23 -25
  12. package/dist/es5/index.js.map +1 -1
  13. package/dist/es5/math-utils.js +5 -11
  14. package/dist/es5/math-utils.js.map +1 -1
  15. package/dist/es5/normalize-viewport-props.js +25 -23
  16. package/dist/es5/normalize-viewport-props.js.map +1 -1
  17. package/dist/es5/web-mercator-utils.js +104 -144
  18. package/dist/es5/web-mercator-utils.js.map +1 -1
  19. package/dist/es5/web-mercator-viewport.js +198 -241
  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 +24 -22
  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.map +1 -1
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm/math-utils.js +3 -3
  29. package/dist/esm/math-utils.js.map +1 -1
  30. package/dist/esm/normalize-viewport-props.js +13 -9
  31. package/dist/esm/normalize-viewport-props.js.map +1 -1
  32. package/dist/esm/web-mercator-utils.js +46 -52
  33. package/dist/esm/web-mercator-utils.js.map +1 -1
  34. package/dist/esm/web-mercator-viewport.js +75 -33
  35. package/dist/esm/web-mercator-viewport.js.map +1 -1
  36. package/dist/fit-bounds.d.ts +49 -0
  37. package/dist/fit-bounds.d.ts.map +1 -0
  38. package/dist/fit-bounds.js +70 -0
  39. package/dist/fly-to-viewport.d.ts +19 -0
  40. package/dist/fly-to-viewport.d.ts.map +1 -0
  41. package/dist/fly-to-viewport.js +87 -0
  42. package/dist/get-bounds.d.ts +3 -0
  43. package/dist/get-bounds.d.ts.map +1 -0
  44. package/dist/get-bounds.js +51 -0
  45. package/dist/index.d.ts +8 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/dist/index.js +8 -0
  48. package/dist/math-utils.d.ts +6 -0
  49. package/dist/math-utils.d.ts.map +1 -0
  50. package/dist/math-utils.js +23 -0
  51. package/dist/normalize-viewport-props.d.ts +17 -0
  52. package/dist/normalize-viewport-props.d.ts.map +1 -0
  53. package/dist/normalize-viewport-props.js +41 -0
  54. package/dist/{es5/web-mercator-utils.d.ts → web-mercator-utils.d.ts} +77 -94
  55. package/dist/web-mercator-utils.d.ts.map +1 -0
  56. package/dist/web-mercator-utils.js +289 -0
  57. package/dist/web-mercator-viewport.d.ts +183 -0
  58. package/dist/web-mercator-viewport.d.ts.map +1 -0
  59. package/dist/web-mercator-viewport.js +282 -0
  60. package/package.json +3 -3
  61. package/src/{assert.js → assert.ts} +1 -1
  62. package/src/fit-bounds.ts +135 -0
  63. package/src/{fly-to-viewport.js → fly-to-viewport.ts} +33 -10
  64. package/src/{get-bounds.js → get-bounds.ts} +4 -2
  65. package/src/{index.js → index.ts} +0 -0
  66. package/src/{math-utils.js → math-utils.ts} +7 -7
  67. package/src/{normalize-viewport-props.js → normalize-viewport-props.ts} +19 -10
  68. package/src/{web-mercator-utils.js → web-mercator-utils.ts} +181 -72
  69. package/src/web-mercator-viewport.ts +417 -0
  70. package/dist/es5/fit-bounds.d.ts +0 -64
  71. package/dist/es5/fly-to-viewport.d.ts +0 -31
  72. package/dist/es5/get-bounds.d.ts +0 -3
  73. package/dist/es5/index.d.ts +0 -23
  74. package/dist/es5/normalize-viewport-props.d.ts +0 -16
  75. package/dist/es5/web-mercator-viewport.d.ts +0 -187
  76. package/dist/esm/fit-bounds.d.ts +0 -64
  77. package/dist/esm/fly-to-viewport.d.ts +0 -31
  78. package/dist/esm/get-bounds.d.ts +0 -3
  79. package/dist/esm/index.d.ts +0 -23
  80. package/dist/esm/normalize-viewport-props.d.ts +0 -16
  81. package/dist/esm/web-mercator-utils.d.ts +0 -189
  82. package/dist/esm/web-mercator-viewport.d.ts +0 -187
  83. package/src/fit-bounds.d.ts +0 -64
  84. package/src/fit-bounds.js +0 -84
  85. package/src/fly-to-viewport.d.ts +0 -31
  86. package/src/get-bounds.d.ts +0 -3
  87. package/src/index.d.ts +0 -23
  88. package/src/normalize-viewport-props.d.ts +0 -16
  89. package/src/web-mercator-utils.d.ts +0 -189
  90. package/src/web-mercator-viewport.d.ts +0 -187
  91. package/src/web-mercator-viewport.js +0 -262
@@ -0,0 +1,183 @@
1
+ import type { FitBoundsOptions } from './fit-bounds';
2
+ /**
3
+ * @param width=1 - Width of "viewport" or window
4
+ * @param height=1 - Height of "viewport" or window
5
+ * @param scale=1 - Either use scale or zoom
6
+ * @param pitch=0 - Camera angle in degrees (0 is straight down)
7
+ * @param bearing=0 - Map rotation in degrees (0 means north is up)
8
+ * @param fovy= - Field of view of camera in degrees
9
+ * @param altitude= - Altitude of camera in screen units
10
+ *
11
+ * Web mercator projection short-hand parameters
12
+ * @param latitude - Center of viewport on map
13
+ * @param longitude - Center of viewport on map
14
+ * @param zoom - Scale = Math.pow(2,zoom) on map
15
+
16
+ * Notes:
17
+ * - Only one of center or [latitude, longitude] can be specified
18
+ * - [latitude, longitude] can only be specified when "mercator" is true
19
+ * - Altitude has a default value that matches assumptions in mapbox-gl
20
+ * - Field of view is independent from altitude, provide `altitudeToFovy(1.5)` (default value) to match assumptions in mapbox-gl
21
+ * - width and height are forced to 1 if supplied as 0, to avoid
22
+ * division by zero. This is intended to reduce the burden of apps to
23
+ * to check values before instantiating a Viewport.
24
+ */
25
+ export declare type WebMercatorViewportProps = {
26
+ width: number;
27
+ height: number;
28
+ latitude?: number;
29
+ longitude?: number;
30
+ position?: number[];
31
+ zoom?: number;
32
+ pitch?: number;
33
+ bearing?: number;
34
+ altitude?: number;
35
+ fovy?: number;
36
+ nearZMultiplier?: number;
37
+ farZMultiplier?: number;
38
+ };
39
+ /**
40
+ * The WebMercatorViewport class creates
41
+ * - view/projection matrices
42
+ * - "uniform values" (for shaders) from mercator params
43
+ *
44
+ * Note: Instances are immutable in the sense that they only have accessors.
45
+ * A new viewport instance should be created if any parameters have changed.
46
+ */
47
+ export default class WebMercatorViewport {
48
+ readonly latitude: number;
49
+ readonly longitude: number;
50
+ readonly zoom: number;
51
+ readonly pitch: number;
52
+ readonly bearing: number;
53
+ readonly altitude: number;
54
+ readonly fovy: number;
55
+ readonly meterOffset: number[];
56
+ readonly center: number[];
57
+ readonly width: number;
58
+ readonly height: number;
59
+ readonly scale: number;
60
+ readonly distanceScales: {
61
+ unitsPerMeter: number[];
62
+ };
63
+ readonly viewMatrix: number[];
64
+ readonly projectionMatrix: number[];
65
+ viewProjectionMatrix: number[];
66
+ pixelProjectionMatrix: number[];
67
+ pixelUnprojectionMatrix: number[];
68
+ /**
69
+ * @classdesc
70
+ * Creates view/projection matrices from mercator params
71
+ * Note: The Viewport is immutable in the sense that it only has accessors.
72
+ * A new viewport instance should be created if any parameters have changed.
73
+ */
74
+ constructor(props?: WebMercatorViewportProps);
75
+ _initMatrices(): void;
76
+ /** Two viewports are equal if width and height are identical, and if
77
+ * their view and projection matrices are (approximately) equal.
78
+ */
79
+ equals(viewport: WebMercatorViewport | null): boolean;
80
+ /**
81
+ * Projects xyz (possibly latitude and longitude) to pixel coordinates in window
82
+ * using viewport projection parameters
83
+ * - [longitude, latitude] to [x, y]
84
+ * - [longitude, latitude, Z] => [x, y, z]
85
+ * Note: By default, returns top-left coordinates for canvas/SVG type render
86
+ *
87
+ * @param lngLatZ - [lng, lat] or [lng, lat, Z]
88
+ * @param options - options
89
+ * @param options.topLeft=true - Whether projected coords are top left
90
+ * @return - screen coordinates [x, y] or [x, y, z], z as pixel depth
91
+ */
92
+ project(lngLatZ: number[], options?: {
93
+ topLeft?: boolean;
94
+ }): number[];
95
+ /**
96
+ * Unproject pixel coordinates on screen onto world coordinates, possibly `[lon, lat]` on map.
97
+ *
98
+ * - [x, y] => [lng, lat]
99
+ * - [x, y, z] => [lng, lat, Z]
100
+ *
101
+ * @param xyz - screen coordinates, z as pixel depth
102
+ * @param options - options
103
+ * @param options.topLeft=true - Whether projected coords are top left
104
+ * @param options.targetZ=0 - If pixel depth is unknown, targetZ is used as
105
+ * the elevation plane to unproject onto
106
+ * @return - [lng, lat, Z] or [X, Y, Z]
107
+ */
108
+ unproject(xyz: number[], options?: {
109
+ topLeft?: boolean;
110
+ targetZ?: number;
111
+ }): number[];
112
+ projectPosition(xyz: any): number[];
113
+ unprojectPosition(xyz: any): number[];
114
+ /**
115
+ * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
116
+ * Performs the nonlinear part of the web mercator projection.
117
+ * Remaining projection is done with 4x4 matrices which also handles
118
+ * perspective.
119
+ *
120
+ * @param lngLat - [lng, lat] coordinates
121
+ * Specifies a point on the sphere to project onto the map.
122
+ * @return [x,y] coordinates.
123
+ */
124
+ projectFlat(lngLat: number[]): number[];
125
+ /**
126
+ * Unproject world point [x,y] on map onto {lat, lon} on sphere
127
+ *
128
+ * @param xy - array with [x,y] members
129
+ * representing point on projected map plane
130
+ * @return - array with [lat,lon] of point on sphere.
131
+ * Has toArray method if you need a GeoJSON Array.
132
+ * Per cartographic tradition, lat and lon are specified as degrees.
133
+ */
134
+ unprojectFlat(xy: number[]): number[];
135
+ /**
136
+ * Get the map center that place a given [lng, lat] coordinate at screen point [x, y]
137
+ * @param opt
138
+ * @param opt.lngLat - [lng,lat] coordinates
139
+ * Specifies a point on the sphere.
140
+ * @param opt.pos - [x,y] coordinates
141
+ * Specifies a point on the screen.
142
+ * @return [lng,lat] new map center.
143
+ */
144
+ getMapCenterByLngLatPosition({ lngLat, pos }: {
145
+ lngLat: number[];
146
+ pos: number[];
147
+ }): number[];
148
+ /**
149
+ * Returns a new viewport that fit around the given rectangle.
150
+ * Only supports non-perspective mode.
151
+ * @param bounds - [[lon, lat], [lon, lat]]
152
+ * @param [options]
153
+ * @param [options.padding] - The amount of padding in pixels to add to the given bounds.
154
+ * @param [options.offset] - The center of the given bounds relative to the map's center,
155
+ * [x, y] measured in pixels.
156
+ * @returns {WebMercatorViewport}
157
+ */
158
+ fitBounds(bounds: [[number, number], [number, number]], options?: Omit<FitBoundsOptions, 'width' | 'height' | 'bounds'>): WebMercatorViewport;
159
+ /**
160
+ * Returns the bounding box of the viewport.
161
+ * @param [options]
162
+ * @param [options.z] - The altitude at which the bounds should be calculated.
163
+ * @returns {Array} bounds - [[lon, lat], [lon, lat]]
164
+ */
165
+ getBounds(options?: {
166
+ z?: number;
167
+ }): number[][];
168
+ /**
169
+ * Returns the bounding box of the viewport.
170
+ * @param [options]
171
+ * @param [options.z] - The altitude at which the bounds should be calculated.
172
+ * @returns {Array} an array of 4 points that define the visible region
173
+ */
174
+ getBoundingRegion(options?: {
175
+ z?: number;
176
+ }): number[][];
177
+ /** @deprecated Legacy method name */
178
+ getLocationAtPoint({ lngLat, pos }: {
179
+ lngLat: number[];
180
+ pos: number[];
181
+ }): number[];
182
+ }
183
+ //# sourceMappingURL=web-mercator-viewport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-mercator-viewport.d.ts","sourceRoot":"","sources":["../src/web-mercator-viewport.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAS,gBAAgB,EAAC,MAAM,cAAc,CAAC;AAM3D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,oBAAY,wBAAwB,GAAG;IAErC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC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,OAAO,GAAE;QAAC,CAAC,CAAC,EAAE,MAAM,CAAA;KAAM,GAAG,MAAM,EAAE,EAAE;IAMzD,qCAAqC;IACrC,kBAAkB,CAAC,EAAC,MAAM,EAAE,GAAG,EAAC,EAAE;QAAC,MAAM,EAAE,MAAM,EAAE,CAAC;QAAC,GAAG,EAAE,MAAM,EAAE,CAAA;KAAC,GAAG,MAAM,EAAE;CAG/E"}
@@ -0,0 +1,282 @@
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[2] = 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
+ // @ts-expect-error
192
+ const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];
193
+ return [X, Y, Z];
194
+ }
195
+ /**
196
+ * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
197
+ * Performs the nonlinear part of the web mercator projection.
198
+ * Remaining projection is done with 4x4 matrices which also handles
199
+ * perspective.
200
+ *
201
+ * @param lngLat - [lng, lat] coordinates
202
+ * Specifies a point on the sphere to project onto the map.
203
+ * @return [x,y] coordinates.
204
+ */
205
+ projectFlat(lngLat) {
206
+ return lngLatToWorld(lngLat);
207
+ }
208
+ /**
209
+ * Unproject world point [x,y] on map onto {lat, lon} on sphere
210
+ *
211
+ * @param xy - array with [x,y] members
212
+ * representing point on projected map plane
213
+ * @return - array with [lat,lon] of point on sphere.
214
+ * Has toArray method if you need a GeoJSON Array.
215
+ * Per cartographic tradition, lat and lon are specified as degrees.
216
+ */
217
+ unprojectFlat(xy) {
218
+ return worldToLngLat(xy);
219
+ }
220
+ /**
221
+ * Get the map center that place a given [lng, lat] coordinate at screen point [x, y]
222
+ * @param opt
223
+ * @param opt.lngLat - [lng,lat] coordinates
224
+ * Specifies a point on the sphere.
225
+ * @param opt.pos - [x,y] coordinates
226
+ * Specifies a point on the screen.
227
+ * @return [lng,lat] new map center.
228
+ */
229
+ getMapCenterByLngLatPosition({ lngLat, pos }) {
230
+ const fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix);
231
+ const toLocation = lngLatToWorld(lngLat);
232
+ const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));
233
+ const newCenter = vec2.add([], this.center, translate);
234
+ return worldToLngLat(newCenter);
235
+ }
236
+ /**
237
+ * Returns a new viewport that fit around the given rectangle.
238
+ * Only supports non-perspective mode.
239
+ * @param bounds - [[lon, lat], [lon, lat]]
240
+ * @param [options]
241
+ * @param [options.padding] - The amount of padding in pixels to add to the given bounds.
242
+ * @param [options.offset] - The center of the given bounds relative to the map's center,
243
+ * [x, y] measured in pixels.
244
+ * @returns {WebMercatorViewport}
245
+ */
246
+ fitBounds(bounds, options = {}) {
247
+ const { width, height } = this;
248
+ const { longitude, latitude, zoom } = fitBounds(Object.assign({ width, height, bounds }, options));
249
+ return new WebMercatorViewport({ width, height, longitude, latitude, zoom });
250
+ }
251
+ /**
252
+ * Returns the bounding box of the viewport.
253
+ * @param [options]
254
+ * @param [options.z] - The altitude at which the bounds should be calculated.
255
+ * @returns {Array} bounds - [[lon, lat], [lon, lat]]
256
+ */
257
+ getBounds(options) {
258
+ const corners = this.getBoundingRegion(options);
259
+ const west = Math.min(...corners.map((p) => p[0]));
260
+ const east = Math.max(...corners.map((p) => p[0]));
261
+ const south = Math.min(...corners.map((p) => p[1]));
262
+ const north = Math.max(...corners.map((p) => p[1]));
263
+ return [
264
+ [west, south],
265
+ [east, north]
266
+ ];
267
+ }
268
+ /**
269
+ * Returns the bounding box of the viewport.
270
+ * @param [options]
271
+ * @param [options.z] - The altitude at which the bounds should be calculated.
272
+ * @returns {Array} an array of 4 points that define the visible region
273
+ */
274
+ getBoundingRegion(options = {}) {
275
+ return getBounds(this, options.z || 0);
276
+ }
277
+ // DEPRECATED
278
+ /** @deprecated Legacy method name */
279
+ getLocationAtPoint({ lngLat, pos }) {
280
+ return this.getMapCenterByLngLatPosition({ lngLat, pos });
281
+ }
282
+ }
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.1",
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": [
@@ -33,5 +33,5 @@
33
33
  "mapbox-gl": "^1.0.0",
34
34
  "mock-browser": "^0.92.14"
35
35
  },
36
- "gitHead": "0e69c70ff2e6373fed84d303cbf8198a6972944f"
36
+ "gitHead": "45386981340895bf201c2ebb76257c9bbffd8ff6"
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,135 @@
1
+ import WebMercatorViewport from './web-mercator-viewport';
2
+ import assert from './assert';
3
+ import {log2} from './math-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
+ export type Bounds = {
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): Bounds {
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 viewport = new WebMercatorViewport({
70
+ width,
71
+ height,
72
+ longitude: 0,
73
+ latitude: 0,
74
+ zoom: 0
75
+ });
76
+
77
+ const nw = viewport.project([west, north]);
78
+ const se = viewport.project([east, south]);
79
+
80
+ // width/height on the Web Mercator plane
81
+ const size = [
82
+ Math.max(Math.abs(se[0] - nw[0]), minExtent),
83
+ Math.max(Math.abs(se[1] - nw[1]), minExtent)
84
+ ];
85
+
86
+ const targetSize = [
87
+ width - padding.left - padding.right - Math.abs(offset[0]) * 2,
88
+ height - padding.top - padding.bottom - Math.abs(offset[1]) * 2
89
+ ];
90
+
91
+ assert(targetSize[0] > 0 && targetSize[1] > 0);
92
+
93
+ // scale = screen pixels per unit on the Web Mercator plane
94
+ const scaleX = targetSize[0] / size[0];
95
+ const scaleY = targetSize[1] / size[1];
96
+
97
+ // Find how much we need to shift the center
98
+ const offsetX = (padding.right - padding.left) / 2 / scaleX;
99
+ const offsetY = (padding.bottom - padding.top) / 2 / scaleY;
100
+
101
+ const center = [(se[0] + nw[0]) / 2 + offsetX, (se[1] + nw[1]) / 2 + offsetY];
102
+
103
+ const centerLngLat = viewport.unproject(center);
104
+ const zoom = Math.min(maxZoom, viewport.zoom + log2(Math.abs(Math.min(scaleX, scaleY))));
105
+
106
+ assert(Number.isFinite(zoom));
107
+
108
+ return {
109
+ longitude: centerLngLat[0],
110
+ latitude: centerLngLat[1],
111
+ zoom
112
+ };
113
+ }
114
+
115
+ // Helpers
116
+ function getPaddingObject(padding: number | Padding = 0): Padding {
117
+ if (typeof padding === 'number') {
118
+ return {
119
+ top: padding,
120
+ bottom: padding,
121
+ left: padding,
122
+ right: padding
123
+ };
124
+ }
125
+
126
+ // Make sure all the required properties are set
127
+ assert(
128
+ Number.isFinite(padding.top) &&
129
+ Number.isFinite(padding.bottom) &&
130
+ Number.isFinite(padding.left) &&
131
+ Number.isFinite(padding.right)
132
+ );
133
+
134
+ return padding;
135
+ }