@math.gl/web-mercator 3.6.0-alpha.8 → 3.6.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.
@@ -1,41 +0,0 @@
1
- import { worldToLngLat } from './web-mercator-utils';
2
- import { mod, log2 } from './math-utils';
3
- // defined by mapbox-gl
4
- const TILE_SIZE = 512;
5
- /**
6
- * Apply mathematical constraints to viewport props
7
- * @param props
8
- */
9
- // eslint-disable-next-line complexity
10
- export default function normalizeViewportProps(props) {
11
- const { width, height, pitch = 0 } = props;
12
- let { longitude, latitude, zoom, bearing = 0 } = props;
13
- // Normalize degrees
14
- if (longitude < -180 || longitude > 180) {
15
- longitude = mod(longitude + 180, 360) - 180;
16
- }
17
- if (bearing < -180 || bearing > 180) {
18
- bearing = mod(bearing + 180, 360) - 180;
19
- }
20
- // Constrain zoom and shift center at low zoom levels
21
- const minZoom = log2(height / TILE_SIZE);
22
- if (zoom <= minZoom) {
23
- zoom = minZoom;
24
- latitude = 0;
25
- }
26
- else {
27
- // Eliminate white space above and below the map
28
- const halfHeightPixels = height / 2 / Math.pow(2, zoom);
29
- const minLatitude = worldToLngLat([0, halfHeightPixels])[1];
30
- if (latitude < minLatitude) {
31
- latitude = minLatitude;
32
- }
33
- else {
34
- const maxLatitude = worldToLngLat([0, TILE_SIZE - halfHeightPixels])[1];
35
- if (latitude > maxLatitude) {
36
- latitude = maxLatitude;
37
- }
38
- }
39
- }
40
- return { width, height, longitude, latitude, zoom, pitch, bearing };
41
- }
@@ -1,290 +0,0 @@
1
- // TODO - THE UTILITIES IN THIS FILE SHOULD BE IMPORTED FROM WEB-MERCATOR-VIEWPORT MODULE
2
- import { createMat4, transformVector, log2 } from './math-utils';
3
- import * as mat4 from 'gl-matrix/mat4';
4
- import * as vec2 from 'gl-matrix/vec2';
5
- import * as vec3 from 'gl-matrix/vec3';
6
- import assert from './assert';
7
- // CONSTANTS
8
- const PI = Math.PI;
9
- const PI_4 = PI / 4;
10
- const DEGREES_TO_RADIANS = PI / 180;
11
- const RADIANS_TO_DEGREES = 180 / PI;
12
- const TILE_SIZE = 512;
13
- // Average circumference (40075 km equatorial, 40007 km meridional)
14
- const EARTH_CIRCUMFERENCE = 40.03e6;
15
- // Latitude that makes a square world, 2 * atan(E ** PI) - PI / 2
16
- export const MAX_LATITUDE = 85.051129;
17
- // Mapbox default altitude
18
- export const DEFAULT_ALTITUDE = 1.5;
19
- /** Logarithimic zoom to linear scale **/
20
- export function zoomToScale(zoom) {
21
- return Math.pow(2, zoom);
22
- }
23
- /** Linear scale to logarithimic zoom **/
24
- export function scaleToZoom(scale) {
25
- return log2(scale);
26
- }
27
- /**
28
- * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
29
- * Performs the nonlinear part of the web mercator projection.
30
- * Remaining projection is done with 4x4 matrices which also handles
31
- * perspective.
32
- *
33
- * @param lngLat - [lng, lat] coordinates
34
- * Specifies a point on the sphere to project onto the map.
35
- * @return [x,y] coordinates.
36
- */
37
- export function lngLatToWorld(lngLat) {
38
- const [lng, lat] = lngLat;
39
- assert(Number.isFinite(lng));
40
- assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, 'invalid latitude');
41
- const lambda2 = lng * DEGREES_TO_RADIANS;
42
- const phi2 = lat * DEGREES_TO_RADIANS;
43
- const x = (TILE_SIZE * (lambda2 + PI)) / (2 * PI);
44
- const y = (TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5)))) / (2 * PI);
45
- return [x, y];
46
- }
47
- /**
48
- * Unproject world point [x,y] on map onto {lat, lon} on sphere
49
- *
50
- * @param xy - array with [x,y] members
51
- * representing point on projected map plane
52
- * @return - array with [x,y] of point on sphere.
53
- * Has toArray method if you need a GeoJSON Array.
54
- * Per cartographic tradition, lat and lon are specified as degrees.
55
- */
56
- export function worldToLngLat(xy) {
57
- const [x, y] = xy;
58
- const lambda2 = (x / TILE_SIZE) * (2 * PI) - PI;
59
- const phi2 = 2 * (Math.atan(Math.exp((y / TILE_SIZE) * (2 * PI) - PI)) - PI_4);
60
- return [lambda2 * RADIANS_TO_DEGREES, phi2 * RADIANS_TO_DEGREES];
61
- }
62
- /**
63
- * Returns the zoom level that gives a 1 meter pixel at a certain latitude
64
- * 1 = C*cos(y)/2^z/TILE_SIZE = C*cos(y)/2^(z+9)
65
- */
66
- export function getMeterZoom(options) {
67
- const { latitude } = options;
68
- assert(Number.isFinite(latitude));
69
- const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
70
- return scaleToZoom(EARTH_CIRCUMFERENCE * latCosine) - 9;
71
- }
72
- /**
73
- * Calculate distance scales in meters around current lat/lon, both for
74
- * degrees and pixels.
75
- * In mercator projection mode, the distance scales vary significantly
76
- * with latitude.
77
- */
78
- export function getDistanceScales(options) {
79
- const { latitude, longitude, highPrecision = false } = options;
80
- assert(Number.isFinite(latitude) && Number.isFinite(longitude));
81
- const worldSize = TILE_SIZE;
82
- const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
83
- /**
84
- * Number of pixels occupied by one degree longitude around current lat/lon:
85
- unitsPerDegreeX = d(lngLatToWorld([lng, lat])[0])/d(lng)
86
- = scale * TILE_SIZE * DEGREES_TO_RADIANS / (2 * PI)
87
- unitsPerDegreeY = d(lngLatToWorld([lng, lat])[1])/d(lat)
88
- = -scale * TILE_SIZE * DEGREES_TO_RADIANS / cos(lat * DEGREES_TO_RADIANS) / (2 * PI)
89
- */
90
- const unitsPerDegreeX = worldSize / 360;
91
- const unitsPerDegreeY = unitsPerDegreeX / latCosine;
92
- /**
93
- * Number of pixels occupied by one meter around current lat/lon:
94
- */
95
- const altUnitsPerMeter = worldSize / EARTH_CIRCUMFERENCE / latCosine;
96
- /**
97
- * LngLat: longitude -> east and latitude -> north (bottom left)
98
- * UTM meter offset: x -> east and y -> north (bottom left)
99
- * World space: x -> east and y -> south (top left)
100
- *
101
- * Y needs to be flipped when converting delta degree/meter to delta pixels
102
- */
103
- const result = {
104
- unitsPerMeter: [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter],
105
- metersPerUnit: [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter],
106
- unitsPerDegree: [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter],
107
- degreesPerUnit: [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter]
108
- };
109
- /**
110
- * Taylor series 2nd order for 1/latCosine
111
- f'(a) * (x - a)
112
- = d(1/cos(lat * DEGREES_TO_RADIANS))/d(lat) * dLat
113
- = DEGREES_TO_RADIANS * tan(lat * DEGREES_TO_RADIANS) / cos(lat * DEGREES_TO_RADIANS) * dLat
114
- */
115
- if (highPrecision) {
116
- const latCosine2 = (DEGREES_TO_RADIANS * Math.tan(latitude * DEGREES_TO_RADIANS)) / latCosine;
117
- const unitsPerDegreeY2 = (unitsPerDegreeX * latCosine2) / 2;
118
- const altUnitsPerDegree2 = (worldSize / EARTH_CIRCUMFERENCE) * latCosine2;
119
- const altUnitsPerMeter2 = (altUnitsPerDegree2 / unitsPerDegreeY) * altUnitsPerMeter;
120
- result.unitsPerDegree2 = [0, unitsPerDegreeY2, altUnitsPerDegree2];
121
- result.unitsPerMeter2 = [altUnitsPerMeter2, 0, altUnitsPerMeter2];
122
- }
123
- // Main results, used for converting meters to latlng deltas and scaling offsets
124
- return result;
125
- }
126
- /**
127
- * Offset a lng/lat position by meterOffset (northing, easting)
128
- */
129
- export function addMetersToLngLat(lngLatZ, xyz) {
130
- const [longitude, latitude, z0] = lngLatZ;
131
- const [x, y, z] = xyz;
132
- const { unitsPerMeter, unitsPerMeter2 } = getDistanceScales({
133
- longitude,
134
- latitude,
135
- highPrecision: true
136
- });
137
- const worldspace = lngLatToWorld(lngLatZ);
138
- worldspace[0] += x * (unitsPerMeter[0] + unitsPerMeter2[0] * y);
139
- worldspace[1] += y * (unitsPerMeter[1] + unitsPerMeter2[1] * y);
140
- const newLngLat = worldToLngLat(worldspace);
141
- const newZ = (z0 || 0) + (z || 0);
142
- return Number.isFinite(z0) || Number.isFinite(z) ? [newLngLat[0], newLngLat[1], newZ] : newLngLat;
143
- }
144
- /**
145
- *
146
- * view and projection matrix creation is intentionally kept compatible with
147
- * mapbox-gl's implementation to ensure that seamless interoperation
148
- * with mapbox and react-map-gl. See: https://github.com/mapbox/mapbox-gl-js
149
- */
150
- export function getViewMatrix(options) {
151
- const {
152
- // Viewport props
153
- height, pitch, bearing, altitude,
154
- // Pre-calculated parameters
155
- scale, center } = options;
156
- // VIEW MATRIX: PROJECTS MERCATOR WORLD COORDINATES
157
- // Note that mercator world coordinates typically need to be flipped
158
- //
159
- // Note: As usual, matrix operation orders should be read in reverse
160
- // since vectors will be multiplied from the right during transformation
161
- const vm = createMat4();
162
- // Move camera to altitude (along the pitch & bearing direction)
163
- mat4.translate(vm, vm, [0, 0, -altitude]);
164
- // Rotate by bearing, and then by pitch (which tilts the view)
165
- mat4.rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS);
166
- mat4.rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS);
167
- const relativeScale = scale / height;
168
- mat4.scale(vm, vm, [relativeScale, relativeScale, relativeScale]);
169
- if (center) {
170
- mat4.translate(vm, vm, vec3.negate([], center));
171
- }
172
- return vm;
173
- }
174
- /**
175
- * Calculates mapbox compatible projection matrix from parameters
176
- *
177
- * @param options.width Width of "viewport" or window
178
- * @param options.height Height of "viewport" or window
179
- * @param options.pitch Camera angle in degrees (0 is straight down)
180
- * @param options.fovy field of view in degrees
181
- * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
182
- * @param options.nearZMultiplier control z buffer
183
- * @param options.farZMultiplier control z buffer
184
- * @returns project parameters object
185
- */
186
- export function getProjectionParameters(options) {
187
- const { width, height, altitude, pitch = 0, nearZMultiplier = 1, farZMultiplier = 1 } = options;
188
- let { fovy = altitudeToFovy(DEFAULT_ALTITUDE) } = options;
189
- // For back-compatibility allow field of view to be
190
- // derived from altitude
191
- if (altitude !== undefined) {
192
- fovy = altitudeToFovy(altitude);
193
- }
194
- const halfFov = 0.5 * fovy * DEGREES_TO_RADIANS;
195
- const focalDistance = fovyToAltitude(fovy);
196
- // Find the distance from the center point to the center top
197
- // in focal distance units using law of sines.
198
- const pitchRadians = pitch * DEGREES_TO_RADIANS;
199
- const topHalfSurfaceDistance = (Math.sin(halfFov) * focalDistance) /
200
- Math.sin(Math.min(Math.max(Math.PI / 2 - pitchRadians - halfFov, 0.01), Math.PI - 0.01));
201
- // Calculate z value of the farthest fragment that should be rendered.
202
- const farZ = Math.sin(pitchRadians) * topHalfSurfaceDistance + focalDistance;
203
- return {
204
- fov: 2 * halfFov,
205
- aspect: width / height,
206
- focalDistance,
207
- near: nearZMultiplier,
208
- far: farZ * farZMultiplier
209
- };
210
- }
211
- /**
212
- * CALCULATE PROJECTION MATRIX: PROJECTS FROM CAMERA (VIEW) SPACE TO CLIPSPACE
213
- *
214
- * To match mapbox's z buffer:
215
- * - \<= 0.28: nearZMultiplier: 0.1, farZmultiplier: 1
216
- * - \>= 0.29: nearZMultiplier: 1 / height, farZMultiplier: 1.01
217
- *
218
- * @param options Viewport options
219
- * @param options.width Width of "viewport" or window
220
- * @param options.height Height of "viewport" or window
221
- * @param options.pitch Camera angle in degrees (0 is straight down)
222
- * @param options.fovy field of view in degrees
223
- * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
224
- * @param options.nearZMultiplier control z buffer
225
- * @param options.farZMultiplier control z buffer
226
- * @returns 4x4 projection matrix
227
- */
228
- export function getProjectionMatrix(options) {
229
- const { fov, aspect, near, far } = getProjectionParameters(options);
230
- const projectionMatrix = mat4.perspective([], fov, // fov in radians
231
- aspect, // aspect ratio
232
- near, // near plane
233
- far // far plane
234
- );
235
- return projectionMatrix;
236
- }
237
- /**
238
- *
239
- * Convert an altitude to field of view such that the
240
- * focal distance is equal to the altitude
241
- *
242
- * @param altitude - altitude of camera in screen units
243
- * @return fovy field of view in degrees
244
- */
245
- export function altitudeToFovy(altitude) {
246
- return 2 * Math.atan(0.5 / altitude) * RADIANS_TO_DEGREES;
247
- }
248
- /**
249
- *
250
- * Convert an field of view such that the
251
- * focal distance is equal to the altitude
252
- *
253
- * @param fovy - field of view in degrees
254
- * @return altitude altitude of camera in screen units
255
- */
256
- export function fovyToAltitude(fovy) {
257
- return 0.5 / Math.tan(0.5 * fovy * DEGREES_TO_RADIANS);
258
- }
259
- // Project flat coordinates to pixels on screen.
260
- export function worldToPixels(xyz, pixelProjectionMatrix) {
261
- const [x, y, z = 0] = xyz;
262
- assert(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z));
263
- return transformVector(pixelProjectionMatrix, [x, y, z, 1]);
264
- }
265
- /**
266
- * Unproject pixels on screen to flat coordinates.
267
- *
268
- * @param xyz - pixel coordinate on screen.
269
- * @param pixelUnprojectionMatrix - unprojection matrix 4x4
270
- * @param targetZ - if pixel coordinate does not have a 3rd component (depth),
271
- * targetZ is used as the elevation plane to unproject onto
272
- * @return [x, y, Z] flat coordinates on 512*512 Mercator Zoom 0 tile.
273
- */
274
- export function pixelsToWorld(xyz, pixelUnprojectionMatrix, targetZ = 0) {
275
- const [x, y, z] = xyz;
276
- assert(Number.isFinite(x) && Number.isFinite(y), 'invalid pixel coordinate');
277
- if (Number.isFinite(z)) {
278
- // Has depth component
279
- const coord = transformVector(pixelUnprojectionMatrix, [x, y, z, 1]);
280
- return coord;
281
- }
282
- // since we don't know the correct projected z value for the point,
283
- // unproject two points to get a line and then find the point on that line with z=0
284
- const coord0 = transformVector(pixelUnprojectionMatrix, [x, y, 0, 1]);
285
- const coord1 = transformVector(pixelUnprojectionMatrix, [x, y, 1, 1]);
286
- const z0 = coord0[2];
287
- const z1 = coord1[2];
288
- const t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0);
289
- return vec2.lerp([], coord0, coord1, t);
290
- }
@@ -1,275 +0,0 @@
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
- /** Two viewports are equal if width and height are identical, and if
27
- * their view and projection matrices are (approximately) equal.
28
- */
29
- this.equals = (viewport) => {
30
- if (!(viewport instanceof WebMercatorViewport)) {
31
- return false;
32
- }
33
- return (viewport.width === this.width &&
34
- viewport.height === this.height &&
35
- mat4.equals(viewport.projectionMatrix, this.projectionMatrix) &&
36
- mat4.equals(viewport.viewMatrix, this.viewMatrix));
37
- };
38
- /**
39
- * Projects xyz (possibly latitude and longitude) to pixel coordinates in window
40
- * using viewport projection parameters
41
- * - [longitude, latitude] to [x, y]
42
- * - [longitude, latitude, Z] => [x, y, z]
43
- * Note: By default, returns top-left coordinates for canvas/SVG type render
44
- *
45
- * @param lngLatZ - [lng, lat] or [lng, lat, Z]
46
- * @param options - options
47
- * @param options.topLeft=true - Whether projected coords are top left
48
- * @return - screen coordinates [x, y] or [x, y, z], z as pixel depth
49
- */
50
- this.project = (lngLatZ, options = {}) => {
51
- const { topLeft = true } = options;
52
- const worldPosition = this.projectPosition(lngLatZ);
53
- const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);
54
- const [x, y] = coord;
55
- const y2 = topLeft ? y : this.height - y;
56
- return lngLatZ.length === 2 ? [x, y2] : [x, y2, coord[2]];
57
- };
58
- /**
59
- * Unproject pixel coordinates on screen onto world coordinates, possibly `[lon, lat]` on map.
60
- *
61
- * - [x, y] => [lng, lat]
62
- * - [x, y, z] => [lng, lat, Z]
63
- *
64
- * @param xyz - screen coordinates, z as pixel depth
65
- * @param options - options
66
- * @param options.topLeft=true - Whether projected coords are top left
67
- * @param options.targetZ=0 - If pixel depth is unknown, targetZ is used as
68
- * the elevation plane to unproject onto
69
- * @return - [lng, lat, Z] or [X, Y, Z]
70
- */
71
- this.unproject = (xyz, options = {}) => {
72
- const { topLeft = true, targetZ = undefined } = options;
73
- const [x, y, z] = xyz;
74
- const y2 = topLeft ? y : this.height - y;
75
- const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];
76
- const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);
77
- const [X, Y, Z] = this.unprojectPosition(coord);
78
- if (Number.isFinite(z)) {
79
- return [X, Y, Z];
80
- }
81
- return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y];
82
- };
83
- // NON_LINEAR PROJECTION HOOKS
84
- // Used for web meractor projection
85
- this.projectPosition = (xyz) => {
86
- const [X, Y] = lngLatToWorld(xyz);
87
- const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];
88
- return [X, Y, Z];
89
- };
90
- this.unprojectPosition = (xyz) => {
91
- const [X, Y] = worldToLngLat(xyz);
92
- const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];
93
- return [X, Y, Z];
94
- };
95
- let {
96
- // Map state
97
- width, height, altitude = null, fovy = null } = props;
98
- const { latitude = 0, longitude = 0, zoom = 0, pitch = 0, bearing = 0, position = null, nearZMultiplier = 0.02, farZMultiplier = 1.01 } = props;
99
- // Silently allow apps to send in 0,0 to facilitate isomorphic render etc
100
- width = width || 1;
101
- height = height || 1;
102
- // `fovy` & `altitude` are independent parameters, one for the
103
- // projection and the latter for the view matrix. In the past,
104
- // the `fovy` was always derived from the `altitude`
105
- if (fovy === null && altitude === null) {
106
- altitude = DEFAULT_ALTITUDE;
107
- fovy = altitudeToFovy(altitude);
108
- }
109
- else if (fovy === null) {
110
- fovy = altitudeToFovy(altitude);
111
- }
112
- else if (altitude === null) {
113
- altitude = fovyToAltitude(fovy);
114
- }
115
- const scale = zoomToScale(zoom);
116
- // Altitude - prevent division by 0
117
- // TODO - just throw an Error instead?
118
- altitude = Math.max(0.75, altitude);
119
- const distanceScales = getDistanceScales({ longitude, latitude });
120
- const center = lngLatToWorld([longitude, latitude]);
121
- center.push(0);
122
- if (position) {
123
- vec3.add(center, center, vec3.mul([], position, distanceScales.unitsPerMeter));
124
- }
125
- this.projectionMatrix = getProjectionMatrix({
126
- width,
127
- height,
128
- pitch,
129
- fovy,
130
- nearZMultiplier,
131
- farZMultiplier
132
- });
133
- this.viewMatrix = getViewMatrix({
134
- height,
135
- scale,
136
- center,
137
- pitch,
138
- bearing,
139
- altitude
140
- });
141
- // Save parameters
142
- this.width = width;
143
- this.height = height;
144
- this.scale = scale;
145
- this.latitude = latitude;
146
- this.longitude = longitude;
147
- this.zoom = zoom;
148
- this.pitch = pitch;
149
- this.bearing = bearing;
150
- this.altitude = altitude;
151
- this.fovy = fovy;
152
- this.center = center;
153
- this.meterOffset = position || [0, 0, 0];
154
- this.distanceScales = distanceScales;
155
- this._initMatrices();
156
- Object.freeze(this);
157
- }
158
- _initMatrices() {
159
- const { width, height, projectionMatrix, viewMatrix } = this;
160
- // Note: As usual, matrix operations should be applied in "reverse" order
161
- // since vectors will be multiplied in from the right during transformation
162
- const vpm = createMat4();
163
- mat4.multiply(vpm, vpm, projectionMatrix);
164
- mat4.multiply(vpm, vpm, viewMatrix);
165
- this.viewProjectionMatrix = vpm;
166
- // Calculate matrices and scales needed for projection
167
- /**
168
- * Builds matrices that converts preprojected lngLats to screen pixels
169
- * and vice versa.
170
- * Note: Currently returns bottom-left coordinates!
171
- * Note: Starts with the GL projection matrix and adds steps to the
172
- * scale and translate that matrix onto the window.
173
- * Note: WebGL controls clip space to screen projection with gl.viewport
174
- * and does not need this step.
175
- */
176
- const m = createMat4();
177
- // matrix for conversion from location to screen coordinates
178
- mat4.scale(m, m, [width / 2, -height / 2, 1]);
179
- mat4.translate(m, m, [1, -1, 0]);
180
- mat4.multiply(m, m, vpm);
181
- const mInverse = mat4.invert(createMat4(), m);
182
- if (!mInverse) {
183
- throw new Error('Pixel project matrix not invertible');
184
- }
185
- this.pixelProjectionMatrix = m;
186
- this.pixelUnprojectionMatrix = mInverse;
187
- }
188
- /**
189
- * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
190
- * Performs the nonlinear part of the web mercator projection.
191
- * Remaining projection is done with 4x4 matrices which also handles
192
- * perspective.
193
- *
194
- * @param lngLat - [lng, lat] coordinates
195
- * Specifies a point on the sphere to project onto the map.
196
- * @return [x,y] coordinates.
197
- */
198
- projectFlat(lngLat) {
199
- return lngLatToWorld(lngLat);
200
- }
201
- /**
202
- * Unproject world point [x,y] on map onto {lat, lon} on sphere
203
- *
204
- * @param xy - array with [x,y] members
205
- * representing point on projected map plane
206
- * @return - array with [lat,lon] of point on sphere.
207
- * Has toArray method if you need a GeoJSON Array.
208
- * Per cartographic tradition, lat and lon are specified as degrees.
209
- */
210
- unprojectFlat(xy) {
211
- return worldToLngLat(xy);
212
- }
213
- /**
214
- * Get the map center that place a given [lng, lat] coordinate at screen point [x, y]
215
- * @param opt
216
- * @param opt.lngLat - [lng,lat] coordinates
217
- * Specifies a point on the sphere.
218
- * @param opt.pos - [x,y] coordinates
219
- * Specifies a point on the screen.
220
- * @return [lng,lat] new map center.
221
- */
222
- getMapCenterByLngLatPosition({ lngLat, pos }) {
223
- const fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix);
224
- const toLocation = lngLatToWorld(lngLat);
225
- const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));
226
- const newCenter = vec2.add([], this.center, translate);
227
- return worldToLngLat(newCenter);
228
- }
229
- /**
230
- * Returns a new viewport that fit around the given rectangle.
231
- * Only supports non-perspective mode.
232
- * @param bounds - [[lon, lat], [lon, lat]]
233
- * @param [options]
234
- * @param [options.padding] - The amount of padding in pixels to add to the given bounds.
235
- * @param [options.offset] - The center of the given bounds relative to the map's center,
236
- * [x, y] measured in pixels.
237
- * @returns {WebMercatorViewport}
238
- */
239
- fitBounds(bounds, options = {}) {
240
- const { width, height } = this;
241
- const { longitude, latitude, zoom } = fitBounds(Object.assign({ width, height, bounds }, options));
242
- return new WebMercatorViewport({ width, height, longitude, latitude, zoom });
243
- }
244
- /**
245
- * Returns the bounding box of the viewport.
246
- * @param [options]
247
- * @param [options.z] - The altitude at which the bounds should be calculated.
248
- * @returns {Array} bounds - [[lon, lat], [lon, lat]]
249
- */
250
- getBounds(options) {
251
- const corners = this.getBoundingRegion(options);
252
- const west = Math.min(...corners.map((p) => p[0]));
253
- const east = Math.max(...corners.map((p) => p[0]));
254
- const south = Math.min(...corners.map((p) => p[1]));
255
- const north = Math.max(...corners.map((p) => p[1]));
256
- return [
257
- [west, south],
258
- [east, north]
259
- ];
260
- }
261
- /**
262
- * Returns the bounding box of the viewport.
263
- * @param [options]
264
- * @param [options.z] - The altitude at which the bounds should be calculated.
265
- * @returns {Array} an array of 4 points that define the visible region
266
- */
267
- getBoundingRegion(options = {}) {
268
- return getBounds(this, options.z || 0);
269
- }
270
- // DEPRECATED
271
- /** @deprecated Legacy method name */
272
- getLocationAtPoint({ lngLat, pos }) {
273
- return this.getMapCenterByLngLatPosition({ lngLat, pos });
274
- }
275
- }