source: josm/trunk/src/org/openstreetmap/josm/data/projection/CustomProjection.java@ 12236

Last change on this file since 12236 was 12236, checked in by Don-vip, 7 years ago

checkstyle - add @deprecated javadoc tag

  • Property svn:eol-style set to native
File size: 35.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.projection;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.EnumMap;
9import java.util.HashMap;
10import java.util.List;
11import java.util.Map;
12import java.util.Optional;
13import java.util.concurrent.ConcurrentHashMap;
14import java.util.regex.Matcher;
15import java.util.regex.Pattern;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.Bounds;
19import org.openstreetmap.josm.data.ProjectionBounds;
20import org.openstreetmap.josm.data.coor.EastNorth;
21import org.openstreetmap.josm.data.coor.LatLon;
22import org.openstreetmap.josm.data.projection.datum.CentricDatum;
23import org.openstreetmap.josm.data.projection.datum.Datum;
24import org.openstreetmap.josm.data.projection.datum.NTV2Datum;
25import org.openstreetmap.josm.data.projection.datum.NullDatum;
26import org.openstreetmap.josm.data.projection.datum.SevenParameterDatum;
27import org.openstreetmap.josm.data.projection.datum.ThreeParameterDatum;
28import org.openstreetmap.josm.data.projection.datum.WGS84Datum;
29import org.openstreetmap.josm.data.projection.proj.ICentralMeridianProvider;
30import org.openstreetmap.josm.data.projection.proj.IScaleFactorProvider;
31import org.openstreetmap.josm.data.projection.proj.Mercator;
32import org.openstreetmap.josm.data.projection.proj.Proj;
33import org.openstreetmap.josm.data.projection.proj.ProjParameters;
34import org.openstreetmap.josm.tools.JosmRuntimeException;
35import org.openstreetmap.josm.tools.Utils;
36import org.openstreetmap.josm.tools.bugreport.BugReport;
37
38/**
39 * Custom projection.
40 *
41 * Inspired by PROJ.4 and Proj4J.
42 * @since 5072
43 */
44public class CustomProjection extends AbstractProjection {
45
46 /*
47 * Equation for METER_PER_UNIT_DEGREE taken from:
48 * https://github.com/openlayers/ol3/blob/master/src/ol/proj/epsg4326projection.js#L58
49 * Value for Radius taken form:
50 * https://github.com/openlayers/ol3/blob/master/src/ol/sphere/wgs84sphere.js#L11
51 */
52 private static final double METER_PER_UNIT_DEGREE = 2 * Math.PI * 6378137.0 / 360;
53 private static final Map<String, Double> UNITS_TO_METERS = getUnitsToMeters();
54 private static final Map<String, Double> PRIME_MERIDANS = getPrimeMeridians();
55
56 /**
57 * pref String that defines the projection
58 *
59 * null means fall back mode (Mercator)
60 */
61 protected String pref;
62 protected String name;
63 protected String code;
64 protected String cacheDir;
65 protected Bounds bounds;
66 private double metersPerUnitWMTS;
67 private String axis = "enu"; // default axis orientation is East, North, Up
68
69 private static final List<String> LON_LAT_VALUES = Arrays.asList("longlat", "latlon", "latlong");
70
71 /**
72 * Proj4-like projection parameters. See <a href="https://trac.osgeo.org/proj/wiki/GenParms">reference</a>.
73 * @since 7370 (public)
74 */
75 public enum Param {
76
77 /** False easting */
78 x_0("x_0", true),
79 /** False northing */
80 y_0("y_0", true),
81 /** Central meridian */
82 lon_0("lon_0", true),
83 /** Prime meridian */
84 pm("pm", true),
85 /** Scaling factor */
86 k_0("k_0", true),
87 /** Ellipsoid name (see {@code proj -le}) */
88 ellps("ellps", true),
89 /** Semimajor radius of the ellipsoid axis */
90 a("a", true),
91 /** Eccentricity of the ellipsoid squared */
92 es("es", true),
93 /** Reciprocal of the ellipsoid flattening term (e.g. 298) */
94 rf("rf", true),
95 /** Flattening of the ellipsoid = 1-sqrt(1-e^2) */
96 f("f", true),
97 /** Semiminor radius of the ellipsoid axis */
98 b("b", true),
99 /** Datum name (see {@code proj -ld}) */
100 datum("datum", true),
101 /** 3 or 7 term datum transform parameters */
102 towgs84("towgs84", true),
103 /** Filename of NTv2 grid file to use for datum transforms */
104 nadgrids("nadgrids", true),
105 /** Projection name (see {@code proj -l}) */
106 proj("proj", true),
107 /** Latitude of origin */
108 lat_0("lat_0", true),
109 /** Latitude of first standard parallel */
110 lat_1("lat_1", true),
111 /** Latitude of second standard parallel */
112 lat_2("lat_2", true),
113 /** Latitude of true scale (Polar Stereographic) */
114 lat_ts("lat_ts", true),
115 /** longitude of the center of the projection (Oblique Mercator) */
116 lonc("lonc", true),
117 /** azimuth (true) of the center line passing through the center of the
118 * projection (Oblique Mercator) */
119 alpha("alpha", true),
120 /** rectified bearing of the center line (Oblique Mercator) */
121 gamma("gamma", true),
122 /** select "Hotine" variant of Oblique Mercator */
123 no_off("no_off", false),
124 /** legacy alias for no_off */
125 no_uoff("no_uoff", false),
126 /** longitude of first point (Oblique Mercator) */
127 lon_1("lon_1", true),
128 /** longitude of second point (Oblique Mercator) */
129 lon_2("lon_2", true),
130 /** the exact proj.4 string will be preserved in the WKT representation */
131 wktext("wktext", false), // ignored
132 /** meters, US survey feet, etc. */
133 units("units", true),
134 /** Don't use the /usr/share/proj/proj_def.dat defaults file */
135 no_defs("no_defs", false),
136 init("init", true),
137 /** crs units to meter multiplier */
138 to_meter("to_meter", true),
139 /** definition of axis for projection */
140 axis("axis", true),
141 /** UTM zone */
142 zone("zone", true),
143 /** indicate southern hemisphere for UTM */
144 south("south", false),
145 /** vertical units - ignore, as we don't use height information */
146 vunits("vunits", true),
147 // JOSM extensions, not present in PROJ.4
148 wmssrs("wmssrs", true),
149 bounds("bounds", true);
150
151 /** Parameter key */
152 public final String key;
153 /** {@code true} if the parameter has a value */
154 public final boolean hasValue;
155
156 /** Map of all parameters by key */
157 static final Map<String, Param> paramsByKey = new ConcurrentHashMap<>();
158 static {
159 for (Param p : Param.values()) {
160 paramsByKey.put(p.key, p);
161 }
162 // alias
163 paramsByKey.put("k", Param.k_0);
164 }
165
166 Param(String key, boolean hasValue) {
167 this.key = key;
168 this.hasValue = hasValue;
169 }
170 }
171
172 enum Polarity {
173 NORTH(LatLon.NORTH_POLE),
174 SOUTH(LatLon.SOUTH_POLE);
175
176 private final LatLon latlon;
177
178 Polarity(LatLon latlon) {
179 this.latlon = latlon;
180 }
181
182 LatLon getLatLon() {
183 return latlon;
184 }
185 }
186
187 private EnumMap<Polarity, EastNorth> polesEN;
188
189 /**
190 * Constructs a new empty {@code CustomProjection}.
191 */
192 public CustomProjection() {
193 // contents can be set later with update()
194 }
195
196 /**
197 * Constructs a new {@code CustomProjection} with given parameters.
198 * @param pref String containing projection parameters
199 * (ex: "+proj=tmerc +lon_0=-3 +k_0=0.9996 +x_0=500000 +ellps=WGS84 +datum=WGS84 +bounds=-8,-5,2,85")
200 */
201 public CustomProjection(String pref) {
202 this(null, null, pref, null);
203 }
204
205 /**
206 * Constructs a new {@code CustomProjection} with given name, code and parameters.
207 *
208 * @param name describe projection in one or two words
209 * @param code unique code for this projection - may be null
210 * @param pref the string that defines the custom projection
211 * @param cacheDir cache directory name
212 */
213 public CustomProjection(String name, String code, String pref, String cacheDir) {
214 this.name = name;
215 this.code = code;
216 this.pref = pref;
217 this.cacheDir = cacheDir;
218 try {
219 update(pref);
220 } catch (ProjectionConfigurationException ex) {
221 Main.trace(ex);
222 try {
223 update(null);
224 } catch (ProjectionConfigurationException ex1) {
225 throw BugReport.intercept(ex1).put("name", name).put("code", code).put("pref", pref);
226 }
227 }
228 }
229
230 /**
231 * Updates this {@code CustomProjection} with given parameters.
232 * @param pref String containing projection parameters (ex: "+proj=lonlat +ellps=WGS84 +datum=WGS84 +bounds=-180,-90,180,90")
233 * @throws ProjectionConfigurationException if {@code pref} cannot be parsed properly
234 */
235 public final void update(String pref) throws ProjectionConfigurationException {
236 this.pref = pref;
237 if (pref == null) {
238 ellps = Ellipsoid.WGS84;
239 datum = WGS84Datum.INSTANCE;
240 proj = new Mercator();
241 bounds = new Bounds(
242 -85.05112877980659, -180.0,
243 85.05112877980659, 180.0, true);
244 } else {
245 Map<String, String> parameters = parseParameterList(pref, false);
246 parameters = resolveInits(parameters, false);
247 ellps = parseEllipsoid(parameters);
248 datum = parseDatum(parameters, ellps);
249 if (ellps == null) {
250 ellps = datum.getEllipsoid();
251 }
252 proj = parseProjection(parameters, ellps);
253 // "utm" is a shortcut for a set of parameters
254 if ("utm".equals(parameters.get(Param.proj.key))) {
255 Integer zone;
256 try {
257 zone = Integer.valueOf(Optional.ofNullable(parameters.get(Param.zone.key)).orElseThrow(
258 () -> new ProjectionConfigurationException(tr("UTM projection (''+proj=utm'') requires ''+zone=...'' parameter."))));
259 } catch (NumberFormatException e) {
260 zone = null;
261 }
262 if (zone == null || zone < 1 || zone > 60)
263 throw new ProjectionConfigurationException(tr("Expected integer value in range 1-60 for ''+zone=...'' parameter."));
264 this.lon0 = 6d * zone - 183d;
265 this.k0 = 0.9996;
266 this.x0 = 500_000;
267 this.y0 = parameters.containsKey(Param.south.key) ? 10_000_000 : 0;
268 }
269 String s = parameters.get(Param.x_0.key);
270 if (s != null) {
271 this.x0 = parseDouble(s, Param.x_0.key);
272 }
273 s = parameters.get(Param.y_0.key);
274 if (s != null) {
275 this.y0 = parseDouble(s, Param.y_0.key);
276 }
277 s = parameters.get(Param.lon_0.key);
278 if (s != null) {
279 this.lon0 = parseAngle(s, Param.lon_0.key);
280 }
281 if (proj instanceof ICentralMeridianProvider) {
282 this.lon0 = ((ICentralMeridianProvider) proj).getCentralMeridian();
283 }
284 s = parameters.get(Param.pm.key);
285 if (s != null) {
286 if (PRIME_MERIDANS.containsKey(s)) {
287 this.pm = PRIME_MERIDANS.get(s);
288 } else {
289 this.pm = parseAngle(s, Param.pm.key);
290 }
291 }
292 s = parameters.get(Param.k_0.key);
293 if (s != null) {
294 this.k0 = parseDouble(s, Param.k_0.key);
295 }
296 if (proj instanceof IScaleFactorProvider) {
297 this.k0 *= ((IScaleFactorProvider) proj).getScaleFactor();
298 }
299 s = parameters.get(Param.bounds.key);
300 if (s != null) {
301 this.bounds = parseBounds(s);
302 }
303 s = parameters.get(Param.wmssrs.key);
304 if (s != null) {
305 this.code = s;
306 }
307 boolean defaultUnits = true;
308 s = parameters.get(Param.units.key);
309 if (s != null) {
310 s = Utils.strip(s, "\"");
311 if (UNITS_TO_METERS.containsKey(s)) {
312 this.toMeter = UNITS_TO_METERS.get(s);
313 this.metersPerUnitWMTS = this.toMeter;
314 defaultUnits = false;
315 } else {
316 throw new ProjectionConfigurationException(tr("No unit found for: {0}", s));
317 }
318 }
319 s = parameters.get(Param.to_meter.key);
320 if (s != null) {
321 this.toMeter = parseDouble(s, Param.to_meter.key);
322 this.metersPerUnitWMTS = this.toMeter;
323 defaultUnits = false;
324 }
325 if (defaultUnits) {
326 this.toMeter = 1;
327 this.metersPerUnitWMTS = proj.isGeographic() ? METER_PER_UNIT_DEGREE : 1;
328 }
329 s = parameters.get(Param.axis.key);
330 if (s != null) {
331 this.axis = s;
332 }
333 }
334 }
335
336 /**
337 * Parse a parameter list to key=value pairs.
338 *
339 * @param pref the parameter list
340 * @param ignoreUnknownParameter true, if unknown parameter should not raise exception
341 * @return parameters map
342 * @throws ProjectionConfigurationException in case of invalid parameter
343 */
344 public static Map<String, String> parseParameterList(String pref, boolean ignoreUnknownParameter) throws ProjectionConfigurationException {
345 Map<String, String> parameters = new HashMap<>();
346 String trimmedPref = pref.trim();
347 if (trimmedPref.isEmpty()) {
348 return parameters;
349 }
350
351 Pattern keyPattern = Pattern.compile("\\+(?<key>[a-zA-Z0-9_]+)(=(?<value>.*))?");
352 String[] parts = Utils.WHITE_SPACES_PATTERN.split(trimmedPref);
353 for (String part : parts) {
354 Matcher m = keyPattern.matcher(part);
355 if (m.matches()) {
356 String key = m.group("key");
357 String value = m.group("value");
358 // some aliases
359 if (key.equals(Param.proj.key) && LON_LAT_VALUES.contains(value)) {
360 value = "lonlat";
361 }
362 Param param = Param.paramsByKey.get(key);
363 if (param == null) {
364 if (!ignoreUnknownParameter)
365 throw new ProjectionConfigurationException(tr("Unknown parameter: ''{0}''.", key));
366 } else {
367 if (param.hasValue && value == null)
368 throw new ProjectionConfigurationException(tr("Value expected for parameter ''{0}''.", key));
369 if (!param.hasValue && value != null)
370 throw new ProjectionConfigurationException(tr("No value expected for parameter ''{0}''.", key));
371 key = param.key; // To be really sure, we might have an alias.
372 }
373 parameters.put(key, value);
374 } else if (!part.startsWith("+")) {
375 throw new ProjectionConfigurationException(tr("Parameter must begin with a ''+'' character (found ''{0}'')", part));
376 } else {
377 throw new ProjectionConfigurationException(tr("Unexpected parameter format (''{0}'')", part));
378 }
379 }
380 return parameters;
381 }
382
383 /**
384 * Recursive resolution of +init includes.
385 *
386 * @param parameters parameters map
387 * @param ignoreUnknownParameter true, if unknown parameter should not raise exception
388 * @return parameters map with +init includes resolved
389 * @throws ProjectionConfigurationException in case of invalid parameter
390 */
391 public static Map<String, String> resolveInits(Map<String, String> parameters, boolean ignoreUnknownParameter)
392 throws ProjectionConfigurationException {
393 // recursive resolution of +init includes
394 String initKey = parameters.get(Param.init.key);
395 if (initKey != null) {
396 Map<String, String> initp;
397 try {
398 initp = parseParameterList(Optional.ofNullable(Projections.getInit(initKey)).orElseThrow(
399 () -> new ProjectionConfigurationException(tr("Value ''{0}'' for option +init not supported.", initKey))),
400 ignoreUnknownParameter);
401 initp = resolveInits(initp, ignoreUnknownParameter);
402 } catch (ProjectionConfigurationException ex) {
403 throw new ProjectionConfigurationException(initKey+": "+ex.getMessage(), ex);
404 }
405 initp.putAll(parameters);
406 return initp;
407 }
408 return parameters;
409 }
410
411 /**
412 * Gets the ellipsoid
413 * @param parameters The parameters to get the value from
414 * @return The Ellipsoid as specified with the parameters
415 * @throws ProjectionConfigurationException in case of invalid parameters
416 */
417 public Ellipsoid parseEllipsoid(Map<String, String> parameters) throws ProjectionConfigurationException {
418 String code = parameters.get(Param.ellps.key);
419 if (code != null) {
420 return Optional.ofNullable(Projections.getEllipsoid(code)).orElseThrow(
421 () -> new ProjectionConfigurationException(tr("Ellipsoid ''{0}'' not supported.", code)));
422 }
423 String s = parameters.get(Param.a.key);
424 if (s != null) {
425 double a = parseDouble(s, Param.a.key);
426 if (parameters.get(Param.es.key) != null) {
427 double es = parseDouble(parameters, Param.es.key);
428 return Ellipsoid.createAes(a, es);
429 }
430 if (parameters.get(Param.rf.key) != null) {
431 double rf = parseDouble(parameters, Param.rf.key);
432 return Ellipsoid.createArf(a, rf);
433 }
434 if (parameters.get(Param.f.key) != null) {
435 double f = parseDouble(parameters, Param.f.key);
436 return Ellipsoid.createAf(a, f);
437 }
438 if (parameters.get(Param.b.key) != null) {
439 double b = parseDouble(parameters, Param.b.key);
440 return Ellipsoid.createAb(a, b);
441 }
442 }
443 if (parameters.containsKey(Param.a.key) ||
444 parameters.containsKey(Param.es.key) ||
445 parameters.containsKey(Param.rf.key) ||
446 parameters.containsKey(Param.f.key) ||
447 parameters.containsKey(Param.b.key))
448 throw new ProjectionConfigurationException(tr("Combination of ellipsoid parameters is not supported."));
449 return null;
450 }
451
452 /**
453 * Gets the datum
454 * @param parameters The parameters to get the value from
455 * @param ellps The ellisoid that was previously computed
456 * @return The Datum as specified with the parameters
457 * @throws ProjectionConfigurationException in case of invalid parameters
458 */
459 public Datum parseDatum(Map<String, String> parameters, Ellipsoid ellps) throws ProjectionConfigurationException {
460 String datumId = parameters.get(Param.datum.key);
461 if (datumId != null) {
462 return Optional.ofNullable(Projections.getDatum(datumId)).orElseThrow(
463 () -> new ProjectionConfigurationException(tr("Unknown datum identifier: ''{0}''", datumId)));
464 }
465 if (ellps == null) {
466 if (parameters.containsKey(Param.no_defs.key))
467 throw new ProjectionConfigurationException(tr("Ellipsoid required (+ellps=* or +a=*, +b=*)"));
468 // nothing specified, use WGS84 as default
469 ellps = Ellipsoid.WGS84;
470 }
471
472 String nadgridsId = parameters.get(Param.nadgrids.key);
473 if (nadgridsId != null) {
474 if (nadgridsId.startsWith("@")) {
475 nadgridsId = nadgridsId.substring(1);
476 }
477 if ("null".equals(nadgridsId))
478 return new NullDatum(null, ellps);
479 final String fNadgridsId = nadgridsId;
480 return new NTV2Datum(fNadgridsId, null, ellps, Optional.ofNullable(Projections.getNTV2Grid(fNadgridsId)).orElseThrow(
481 () -> new ProjectionConfigurationException(tr("Grid shift file ''{0}'' for option +nadgrids not supported.", fNadgridsId))));
482 }
483
484 String towgs84 = parameters.get(Param.towgs84.key);
485 if (towgs84 != null)
486 return parseToWGS84(towgs84, ellps);
487
488 return new NullDatum(null, ellps);
489 }
490
491 /**
492 * Parse {@code towgs84} parameter.
493 * @param paramList List of parameter arguments (expected: 3 or 7)
494 * @param ellps ellipsoid
495 * @return parsed datum ({@link ThreeParameterDatum} or {@link SevenParameterDatum})
496 * @throws ProjectionConfigurationException if the arguments cannot be parsed
497 */
498 public Datum parseToWGS84(String paramList, Ellipsoid ellps) throws ProjectionConfigurationException {
499 String[] numStr = paramList.split(",");
500
501 if (numStr.length != 3 && numStr.length != 7)
502 throw new ProjectionConfigurationException(tr("Unexpected number of arguments for parameter ''towgs84'' (must be 3 or 7)"));
503 List<Double> towgs84Param = new ArrayList<>();
504 for (String str : numStr) {
505 try {
506 towgs84Param.add(Double.valueOf(str));
507 } catch (NumberFormatException e) {
508 throw new ProjectionConfigurationException(tr("Unable to parse value of parameter ''towgs84'' (''{0}'')", str), e);
509 }
510 }
511 boolean isCentric = true;
512 for (Double param : towgs84Param) {
513 if (param != 0) {
514 isCentric = false;
515 break;
516 }
517 }
518 if (isCentric)
519 return new CentricDatum(null, null, ellps);
520 boolean is3Param = true;
521 for (int i = 3; i < towgs84Param.size(); i++) {
522 if (towgs84Param.get(i) != 0) {
523 is3Param = false;
524 break;
525 }
526 }
527 if (is3Param)
528 return new ThreeParameterDatum(null, null, ellps,
529 towgs84Param.get(0),
530 towgs84Param.get(1),
531 towgs84Param.get(2));
532 else
533 return new SevenParameterDatum(null, null, ellps,
534 towgs84Param.get(0),
535 towgs84Param.get(1),
536 towgs84Param.get(2),
537 towgs84Param.get(3),
538 towgs84Param.get(4),
539 towgs84Param.get(5),
540 towgs84Param.get(6));
541 }
542
543 /**
544 * Gets a projection using the given ellipsoid
545 * @param parameters Additional parameters
546 * @param ellps The {@link Ellipsoid}
547 * @return The projection
548 * @throws ProjectionConfigurationException in case of invalid parameters
549 */
550 public Proj parseProjection(Map<String, String> parameters, Ellipsoid ellps) throws ProjectionConfigurationException {
551 String id = parameters.get(Param.proj.key);
552 if (id == null) throw new ProjectionConfigurationException(tr("Projection required (+proj=*)"));
553
554 // "utm" is not a real projection, but a shortcut for a set of parameters
555 if ("utm".equals(id)) {
556 id = "tmerc";
557 }
558 Proj proj = Projections.getBaseProjection(id);
559 if (proj == null) throw new ProjectionConfigurationException(tr("Unknown projection identifier: ''{0}''", id));
560
561 ProjParameters projParams = new ProjParameters();
562
563 projParams.ellps = ellps;
564
565 String s;
566 s = parameters.get(Param.lat_0.key);
567 if (s != null) {
568 projParams.lat0 = parseAngle(s, Param.lat_0.key);
569 }
570 s = parameters.get(Param.lat_1.key);
571 if (s != null) {
572 projParams.lat1 = parseAngle(s, Param.lat_1.key);
573 }
574 s = parameters.get(Param.lat_2.key);
575 if (s != null) {
576 projParams.lat2 = parseAngle(s, Param.lat_2.key);
577 }
578 s = parameters.get(Param.lat_ts.key);
579 if (s != null) {
580 projParams.lat_ts = parseAngle(s, Param.lat_ts.key);
581 }
582 s = parameters.get(Param.lonc.key);
583 if (s != null) {
584 projParams.lonc = parseAngle(s, Param.lonc.key);
585 }
586 s = parameters.get(Param.alpha.key);
587 if (s != null) {
588 projParams.alpha = parseAngle(s, Param.alpha.key);
589 }
590 s = parameters.get(Param.gamma.key);
591 if (s != null) {
592 projParams.gamma = parseAngle(s, Param.gamma.key);
593 }
594 s = parameters.get(Param.lon_1.key);
595 if (s != null) {
596 projParams.lon1 = parseAngle(s, Param.lon_1.key);
597 }
598 s = parameters.get(Param.lon_2.key);
599 if (s != null) {
600 projParams.lon2 = parseAngle(s, Param.lon_2.key);
601 }
602 if (parameters.containsKey(Param.no_off.key) || parameters.containsKey(Param.no_uoff.key)) {
603 projParams.no_off = Boolean.TRUE;
604 }
605 proj.initialize(projParams);
606 return proj;
607 }
608
609 /**
610 * Converts a string to a bounds object
611 * @param boundsStr The string as comma separated list of angles.
612 * @return The bounds.
613 * @throws ProjectionConfigurationException in case of invalid parameter
614 * @see CustomProjection#parseAngle(String, String)
615 */
616 public static Bounds parseBounds(String boundsStr) throws ProjectionConfigurationException {
617 String[] numStr = boundsStr.split(",");
618 if (numStr.length != 4)
619 throw new ProjectionConfigurationException(tr("Unexpected number of arguments for parameter ''+bounds'' (must be 4)"));
620 return new Bounds(parseAngle(numStr[1], "minlat (+bounds)"),
621 parseAngle(numStr[0], "minlon (+bounds)"),
622 parseAngle(numStr[3], "maxlat (+bounds)"),
623 parseAngle(numStr[2], "maxlon (+bounds)"), false);
624 }
625
626 public static double parseDouble(Map<String, String> parameters, String parameterName) throws ProjectionConfigurationException {
627 if (!parameters.containsKey(parameterName))
628 throw new ProjectionConfigurationException(tr("Unknown parameter ''{0}''", parameterName));
629 return parseDouble(Optional.ofNullable(parameters.get(parameterName)).orElseThrow(
630 () -> new ProjectionConfigurationException(tr("Expected number argument for parameter ''{0}''", parameterName))),
631 parameterName);
632 }
633
634 public static double parseDouble(String doubleStr, String parameterName) throws ProjectionConfigurationException {
635 try {
636 return Double.parseDouble(doubleStr);
637 } catch (NumberFormatException e) {
638 throw new ProjectionConfigurationException(
639 tr("Unable to parse value ''{1}'' of parameter ''{0}'' as number.", parameterName, doubleStr), e);
640 }
641 }
642
643 /**
644 * Convert an angle string to a double value
645 * @param angleStr The string. e.g. -1.1 or 50d 10' 3"
646 * @param parameterName Only for error message.
647 * @return The angle value, in degrees.
648 * @throws ProjectionConfigurationException in case of invalid parameter
649 */
650 public static double parseAngle(String angleStr, String parameterName) throws ProjectionConfigurationException {
651 final String floatPattern = "(\\d+(\\.\\d*)?)";
652 // pattern does all error handling.
653 Matcher in = Pattern.compile("^(?<neg1>-)?"
654 + "(?=\\d)(?:(?<single>" + floatPattern + ")|"
655 + "((?<degree>" + floatPattern + ")d)?"
656 + "((?<minutes>" + floatPattern + ")\')?"
657 + "((?<seconds>" + floatPattern + ")\")?)"
658 + "(?:[NE]|(?<neg2>[SW]))?$").matcher(angleStr);
659
660 if (!in.find()) {
661 throw new ProjectionConfigurationException(
662 tr("Unable to parse value ''{1}'' of parameter ''{0}'' as coordinate value.", parameterName, angleStr));
663 }
664
665 double value = 0;
666 if (in.group("single") != null) {
667 value += Double.parseDouble(in.group("single"));
668 }
669 if (in.group("degree") != null) {
670 value += Double.parseDouble(in.group("degree"));
671 }
672 if (in.group("minutes") != null) {
673 value += Double.parseDouble(in.group("minutes")) / 60;
674 }
675 if (in.group("seconds") != null) {
676 value += Double.parseDouble(in.group("seconds")) / 3600;
677 }
678
679 if (in.group("neg1") != null ^ in.group("neg2") != null) {
680 value = -value;
681 }
682 return value;
683 }
684
685 @Override
686 public Integer getEpsgCode() {
687 if (code != null && code.startsWith("EPSG:")) {
688 try {
689 return Integer.valueOf(code.substring(5));
690 } catch (NumberFormatException e) {
691 Main.warn(e);
692 }
693 }
694 return null;
695 }
696
697 @Override
698 public String toCode() {
699 if (code != null) {
700 return code;
701 } else if (pref != null) {
702 return "proj:" + pref;
703 } else {
704 return "proj:ERROR";
705 }
706 }
707
708 /**
709 * {@inheritDoc}
710 * @deprecated unused - remove in 2017-07
711 */
712 @Override
713 @Deprecated
714 public String getCacheDirectoryName() {
715 if (cacheDir != null) {
716 return cacheDir;
717 } else {
718 return "proj-" + Utils.md5Hex(pref == null ? "" : pref).substring(0, 4);
719 }
720 }
721
722 @Override
723 public Bounds getWorldBoundsLatLon() {
724 if (bounds == null) {
725 Bounds ab = proj.getAlgorithmBounds();
726 if (ab != null) {
727 double minlon = Math.max(ab.getMinLon() + lon0 + pm, -180);
728 double maxlon = Math.min(ab.getMaxLon() + lon0 + pm, 180);
729 bounds = new Bounds(ab.getMinLat(), minlon, ab.getMaxLat(), maxlon, false);
730 } else {
731 bounds = new Bounds(
732 new LatLon(-90.0, -180.0),
733 new LatLon(90.0, 180.0));
734 }
735 }
736 return bounds;
737 }
738
739 @Override
740 public String toString() {
741 return name != null ? name : tr("Custom Projection");
742 }
743
744 /**
745 * Factor to convert units of east/north coordinates to meters.
746 *
747 * When east/north coordinates are in degrees (geographic CRS), the scale
748 * at the equator is taken, i.e. 360 degrees corresponds to the length of
749 * the equator in meters.
750 *
751 * @return factor to convert units to meter
752 */
753 @Override
754 public double getMetersPerUnit() {
755 return metersPerUnitWMTS;
756 }
757
758 @Override
759 public boolean switchXY() {
760 // TODO: support for other axis orientation such as West South, and Up Down
761 return this.axis.startsWith("ne");
762 }
763
764 private static Map<String, Double> getUnitsToMeters() {
765 Map<String, Double> ret = new ConcurrentHashMap<>();
766 ret.put("km", 1000d);
767 ret.put("m", 1d);
768 ret.put("dm", 1d/10);
769 ret.put("cm", 1d/100);
770 ret.put("mm", 1d/1000);
771 ret.put("kmi", 1852.0);
772 ret.put("in", 0.0254);
773 ret.put("ft", 0.3048);
774 ret.put("yd", 0.9144);
775 ret.put("mi", 1609.344);
776 ret.put("fathom", 1.8288);
777 ret.put("chain", 20.1168);
778 ret.put("link", 0.201168);
779 ret.put("us-in", 1d/39.37);
780 ret.put("us-ft", 0.304800609601219);
781 ret.put("us-yd", 0.914401828803658);
782 ret.put("us-ch", 20.11684023368047);
783 ret.put("us-mi", 1609.347218694437);
784 ret.put("ind-yd", 0.91439523);
785 ret.put("ind-ft", 0.30479841);
786 ret.put("ind-ch", 20.11669506);
787 ret.put("degree", METER_PER_UNIT_DEGREE);
788 return ret;
789 }
790
791 private static Map<String, Double> getPrimeMeridians() {
792 Map<String, Double> ret = new ConcurrentHashMap<>();
793 try {
794 ret.put("greenwich", 0.0);
795 ret.put("lisbon", parseAngle("9d07'54.862\"W", null));
796 ret.put("paris", parseAngle("2d20'14.025\"E", null));
797 ret.put("bogota", parseAngle("74d04'51.3\"W", null));
798 ret.put("madrid", parseAngle("3d41'16.58\"W", null));
799 ret.put("rome", parseAngle("12d27'8.4\"E", null));
800 ret.put("bern", parseAngle("7d26'22.5\"E", null));
801 ret.put("jakarta", parseAngle("106d48'27.79\"E", null));
802 ret.put("ferro", parseAngle("17d40'W", null));
803 ret.put("brussels", parseAngle("4d22'4.71\"E", null));
804 ret.put("stockholm", parseAngle("18d3'29.8\"E", null));
805 ret.put("athens", parseAngle("23d42'58.815\"E", null));
806 ret.put("oslo", parseAngle("10d43'22.5\"E", null));
807 } catch (ProjectionConfigurationException ex) {
808 throw new IllegalStateException(ex);
809 }
810 return ret;
811 }
812
813 private static EastNorth getPointAlong(int i, int n, ProjectionBounds r) {
814 double dEast = (r.maxEast - r.minEast) / n;
815 double dNorth = (r.maxNorth - r.minNorth) / n;
816 if (i < n) {
817 return new EastNorth(r.minEast + i * dEast, r.minNorth);
818 } else if (i < 2*n) {
819 i -= n;
820 return new EastNorth(r.maxEast, r.minNorth + i * dNorth);
821 } else if (i < 3*n) {
822 i -= 2*n;
823 return new EastNorth(r.maxEast - i * dEast, r.maxNorth);
824 } else if (i < 4*n) {
825 i -= 3*n;
826 return new EastNorth(r.minEast, r.maxNorth - i * dNorth);
827 } else {
828 throw new AssertionError();
829 }
830 }
831
832 private EastNorth getPole(Polarity whichPole) {
833 if (polesEN == null) {
834 polesEN = new EnumMap<>(Polarity.class);
835 for (Polarity p : Polarity.values()) {
836 polesEN.put(p, null);
837 LatLon ll = p.getLatLon();
838 try {
839 EastNorth enPole = latlon2eastNorth(ll);
840 if (enPole.isValid()) {
841 // project back and check if the result is somewhat reasonable
842 LatLon llBack = eastNorth2latlon(enPole);
843 if (llBack.isValid() && ll.greatCircleDistance(llBack) < 1000) {
844 polesEN.put(p, enPole);
845 }
846 }
847 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
848 Main.error(e);
849 }
850 }
851 }
852 return polesEN.get(whichPole);
853 }
854
855 @Override
856 public Bounds getLatLonBoundsBox(ProjectionBounds r) {
857 final int n = 10;
858 Bounds result = new Bounds(eastNorth2latlon(r.getMin()));
859 result.extend(eastNorth2latlon(r.getMax()));
860 LatLon llPrev = null;
861 for (int i = 0; i < 4*n; i++) {
862 LatLon llNow = eastNorth2latlon(getPointAlong(i, n, r));
863 result.extend(llNow);
864 // check if segment crosses 180th meridian and if so, make sure
865 // to extend bounds to +/-180 degrees longitude
866 if (llPrev != null) {
867 double lon1 = llPrev.lon();
868 double lon2 = llNow.lon();
869 if (90 < lon1 && lon1 < 180 && -180 < lon2 && lon2 < -90) {
870 result.extend(new LatLon(llPrev.lat(), 180));
871 result.extend(new LatLon(llNow.lat(), -180));
872 }
873 if (90 < lon2 && lon2 < 180 && -180 < lon1 && lon1 < -90) {
874 result.extend(new LatLon(llNow.lat(), 180));
875 result.extend(new LatLon(llPrev.lat(), -180));
876 }
877 }
878 llPrev = llNow;
879 }
880 // if the box contains one of the poles, the above method did not get
881 // correct min/max latitude value
882 for (Polarity p : Polarity.values()) {
883 EastNorth pole = getPole(p);
884 if (pole != null && r.contains(pole)) {
885 result.extend(p.getLatLon());
886 }
887 }
888 return result;
889 }
890
891 @Override
892 public ProjectionBounds getEastNorthBoundsBox(ProjectionBounds box, Projection boxProjection) {
893 final int n = 8;
894 ProjectionBounds result = null;
895 for (int i = 0; i < 4*n; i++) {
896 EastNorth en = latlon2eastNorth(boxProjection.eastNorth2latlon(getPointAlong(i, n, box)));
897 if (result == null) {
898 result = new ProjectionBounds(en);
899 } else {
900 result.extend(en);
901 }
902 }
903 return result;
904 }
905}
Note: See TracBrowser for help on using the repository browser.