-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
proj4.js
225 lines (211 loc) · 6.59 KB
/
proj4.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
/**
* @module ol/proj/proj4
*/
import Projection from './Projection.js';
import {
addCoordinateTransforms,
addEquivalentProjections,
addProjection,
createSafeCoordinateTransform,
get,
} from '../proj.js';
import {get as getTransform} from './transforms.js';
/**
* @type {import("proj4")|null}
*/
let registered = null;
/**
* @return {boolean} Proj4 has been registered.
*/
export function isRegistered() {
return !!registered;
}
/**
* Unsets the shared proj4 previously set with register.
*/
export function unregister() {
registered = null;
}
/**
* Make projections defined in proj4 (with `proj4.defs()`) available in
* OpenLayers. Requires proj4 >= 2.8.0.
*
* This function should be called whenever changes are made to the proj4
* registry, e.g. after calling `proj4.defs()`. Existing transforms will not be
* modified by this function.
*
* @param {import("proj4")} proj4 Proj4.
* @api
*/
export function register(proj4) {
registered = proj4;
const projCodes = Object.keys(proj4.defs);
const len = projCodes.length;
let i, j;
for (i = 0; i < len; ++i) {
const code = projCodes[i];
if (!get(code)) {
const def = proj4.defs(code);
let units = /** @type {import("./Units.js").Units} */ (def.units);
if (!units && def.projName === 'longlat') {
units = 'degrees';
}
addProjection(
new Projection({
code: code,
axisOrientation: def.axis,
metersPerUnit: def.to_meter,
units,
}),
);
}
}
for (i = 0; i < len; ++i) {
const code1 = projCodes[i];
const proj1 = get(code1);
for (j = 0; j < len; ++j) {
const code2 = projCodes[j];
const proj2 = get(code2);
if (!getTransform(code1, code2)) {
if (proj4.defs[code1] === proj4.defs[code2]) {
addEquivalentProjections([proj1, proj2]);
} else {
const transform = proj4(code1, code2);
addCoordinateTransforms(
proj1,
proj2,
createSafeCoordinateTransform(proj1, proj2, transform.forward),
createSafeCoordinateTransform(proj2, proj1, transform.inverse),
);
}
}
}
}
}
/**
* @param {number} code The EPSG code.
* @return {Promise<string>} The proj4 definition.
*/
let epsgLookup = async function (code) {
const response = await fetch(`https://epsg.io/${code}.proj4`);
if (!response.ok) {
throw new Error(`Unexpected response from epsg.io: ${response.status}`);
}
return response.text();
};
/**
* Set the lookup function for getting proj4 definitions given an EPSG code.
* By default, the {@link module:ol/proj/proj4.fromEPSGCode} function uses the
* epsg.io website for proj4 definitions. This can be changed by providing a
* different lookup function.
*
* @param {function(number):Promise<string>} func The lookup function.
* @api
*/
export function setEPSGLookup(func) {
epsgLookup = func;
}
/**
* Get the current EPSG lookup function.
*
* @return {function(number):Promise<string>} The EPSG lookup function.
*/
export function getEPSGLookup() {
return epsgLookup;
}
/**
* Get a projection from an EPSG code. This function fetches the projection
* definition from the epsg.io website, registers this definition for use with
* proj4, and returns a configured projection. You must call import proj4 and
* call {@link module:ol/proj/proj4.register} before using this function.
*
* If the projection definition is already registered with proj4, it will not
* be fetched again (so it is ok to call this function multiple times with the
* same code).
*
* @param {number|string} code The EPSG code (e.g. 4326 or 'EPSG:4326').
* @return {Promise<Projection>} The projection.
* @api
*/
export async function fromEPSGCode(code) {
if (typeof code === 'string') {
code = parseInt(code.split(':').pop(), 10);
}
const proj4 = registered;
if (!proj4) {
throw new Error('Proj4 must be registered first with register(proj4)');
}
const epsgCode = 'EPSG:' + code;
if (proj4.defs(epsgCode)) {
return get(epsgCode);
}
proj4.defs(epsgCode, await epsgLookup(code));
register(proj4);
return get(epsgCode);
}
/**
* Generate an EPSG lookup function which uses the MapTiler Coordinates API to find projection
* definitions which do not require proj4 to be configured to handle `+nadgrids` parameters.
* Call {@link module:ol/proj/proj4.setEPSGLookup} use the function for lookups
* `setEPSGLookup(epsgLookupMapTiler('{YOUR_MAPTILER_API_KEY_HERE}'))`.
*
* @param {string} key MapTiler API key. Get your own API key at https://www.maptiler.com/cloud/.
* @return {function(number):Promise<string>} The EPSG lookup function.
* @api
*/
export function epsgLookupMapTiler(key) {
return async function (code) {
const response = await fetch(
`https://api.maptiler.com/coordinates/search/code:${code}.json?transformations=true&exports=true&key=${key}`,
);
if (!response.ok) {
throw new Error(
`Unexpected response from maptiler.com: ${response.status}`,
);
}
return response.json().then((json) => {
const results = json['results'];
if (results?.length > 0) {
const result = results.filter(
(r) =>
r['id']?.['authority'] === 'EPSG' && r['id']?.['code'] === code,
)[0];
if (result) {
const transforms = result['transformations'];
if (transforms?.length > 0) {
// use default transform if it does not require grids
const defaultTransform = result['default_transformation'];
if (
transforms.filter(
(t) =>
t['id']?.['authority'] === defaultTransform?.['authority'] &&
t['id']?.['code'] === defaultTransform?.['code'] &&
t['grids']?.length === 0,
).length > 0
) {
return result['exports']?.['proj4'];
}
// otherwise use most accurate alternative without grids
const transform = transforms
.filter(
(t) =>
t['grids']?.length === 0 &&
t['target_crs']?.['authority'] === 'EPSG' &&
t['target_crs']?.['code'] === 4326 &&
t['deprecated'] === false &&
t['usable'] === true,
)
.sort((t1, t2) => t1['accuracy'] - t2['accuracy'])[0]?.[
'exports'
]?.['proj4'];
if (transform) {
return transform;
}
}
// fallback to default
return result['exports']?.['proj4'];
}
}
});
};
}