source: josm/trunk/src/org/openstreetmap/josm/data/projection/Projections.java@ 12778

Last change on this file since 12778 was 12778, checked in by bastiK, 8 years ago

see #15229 - deprecate Projections#project and Projections#inverseProject

replacement is a bit more verbose, but the fact that Main.proj is
involved need not be hidden

  • Property svn:eol-style set to native
File size: 16.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.projection;
3
4import java.io.BufferedReader;
5import java.io.IOException;
6import java.util.ArrayList;
7import java.util.Collection;
8import java.util.Collections;
9import java.util.HashMap;
10import java.util.HashSet;
11import java.util.LinkedHashMap;
12import java.util.List;
13import java.util.Locale;
14import java.util.Map;
15import java.util.Set;
16import java.util.regex.Matcher;
17import java.util.regex.Pattern;
18
19import org.openstreetmap.josm.Main;
20import org.openstreetmap.josm.data.coor.EastNorth;
21import org.openstreetmap.josm.data.coor.ILatLon;
22import org.openstreetmap.josm.data.coor.LatLon;
23import org.openstreetmap.josm.data.projection.datum.Datum;
24import org.openstreetmap.josm.data.projection.datum.GRS80Datum;
25import org.openstreetmap.josm.data.projection.datum.NTV2GridShiftFileWrapper;
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.AlbersEqualArea;
30import org.openstreetmap.josm.data.projection.proj.CassiniSoldner;
31import org.openstreetmap.josm.data.projection.proj.ClassProjFactory;
32import org.openstreetmap.josm.data.projection.proj.DoubleStereographic;
33import org.openstreetmap.josm.data.projection.proj.LambertAzimuthalEqualArea;
34import org.openstreetmap.josm.data.projection.proj.LambertConformalConic;
35import org.openstreetmap.josm.data.projection.proj.LonLat;
36import org.openstreetmap.josm.data.projection.proj.Mercator;
37import org.openstreetmap.josm.data.projection.proj.ObliqueMercator;
38import org.openstreetmap.josm.data.projection.proj.PolarStereographic;
39import org.openstreetmap.josm.data.projection.proj.Proj;
40import org.openstreetmap.josm.data.projection.proj.ProjFactory;
41import org.openstreetmap.josm.data.projection.proj.Sinusoidal;
42import org.openstreetmap.josm.data.projection.proj.SwissObliqueMercator;
43import org.openstreetmap.josm.data.projection.proj.TransverseMercator;
44import org.openstreetmap.josm.gui.preferences.projection.ProjectionChoice;
45import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
46import org.openstreetmap.josm.io.CachedFile;
47import org.openstreetmap.josm.tools.JosmRuntimeException;
48import org.openstreetmap.josm.tools.Logging;
49import org.openstreetmap.josm.tools.Utils;
50
51/**
52 * Class to manage projections.
53 *
54 * Use this class to query available projection or register new projections from a plugin.
55 */
56public final class Projections {
57
58 /**
59 * Class to hold information about one projection.
60 */
61 public static class ProjectionDefinition {
62 public final String code;
63 public final String name;
64 public final String definition;
65
66 /**
67 * Constructs a new {@code ProjectionDefinition}.
68 * @param code EPSG code
69 * @param name projection name
70 * @param definition projection definition (EPSG format)
71 */
72 public ProjectionDefinition(String code, String name, String definition) {
73 this.code = code;
74 this.name = name;
75 this.definition = definition;
76 }
77 }
78
79 private static final Set<String> allCodes = new HashSet<>();
80 private static final Map<String, ProjectionChoice> allProjectionChoicesByCode = new HashMap<>();
81 private static final Map<String, Projection> projectionsByCode_cache = new HashMap<>();
82
83 /*********************************
84 * Registry for custom projection
85 *
86 * should be compatible to PROJ.4
87 */
88 private static final Map<String, ProjFactory> projs = new HashMap<>();
89 private static final Map<String, Ellipsoid> ellipsoids = new HashMap<>();
90 private static final Map<String, Datum> datums = new HashMap<>();
91 private static final Map<String, NTV2GridShiftFileWrapper> nadgrids = new HashMap<>();
92 private static final Map<String, ProjectionDefinition> inits;
93
94 static {
95 registerBaseProjection("aea", AlbersEqualArea.class, "core");
96 registerBaseProjection("cass", CassiniSoldner.class, "core");
97 registerBaseProjection("laea", LambertAzimuthalEqualArea.class, "core");
98 registerBaseProjection("lcc", LambertConformalConic.class, "core");
99 registerBaseProjection("lonlat", LonLat.class, "core");
100 registerBaseProjection("merc", Mercator.class, "core");
101 registerBaseProjection("omerc", ObliqueMercator.class, "core");
102 registerBaseProjection("somerc", SwissObliqueMercator.class, "core");
103 registerBaseProjection("sinu", Sinusoidal.class, "core");
104 registerBaseProjection("stere", PolarStereographic.class, "core");
105 registerBaseProjection("sterea", DoubleStereographic.class, "core");
106 registerBaseProjection("tmerc", TransverseMercator.class, "core");
107
108 ellipsoids.put("airy", Ellipsoid.Airy);
109 ellipsoids.put("mod_airy", Ellipsoid.AiryMod);
110 ellipsoids.put("aust_SA", Ellipsoid.AustSA);
111 ellipsoids.put("bessel", Ellipsoid.Bessel1841);
112 ellipsoids.put("bess_nam", Ellipsoid.BesselNamibia);
113 ellipsoids.put("clrk66", Ellipsoid.Clarke1866);
114 ellipsoids.put("clrk80", Ellipsoid.Clarke1880);
115 ellipsoids.put("clrk80ign", Ellipsoid.ClarkeIGN);
116 ellipsoids.put("evrstSS", Ellipsoid.EverestSabahSarawak);
117 ellipsoids.put("intl", Ellipsoid.Hayford);
118 ellipsoids.put("helmert", Ellipsoid.Helmert);
119 ellipsoids.put("krass", Ellipsoid.Krassowsky);
120 ellipsoids.put("GRS67", Ellipsoid.GRS67);
121 ellipsoids.put("GRS80", Ellipsoid.GRS80);
122 ellipsoids.put("WGS66", Ellipsoid.WGS66);
123 ellipsoids.put("WGS72", Ellipsoid.WGS72);
124 ellipsoids.put("WGS84", Ellipsoid.WGS84);
125
126 datums.put("WGS84", WGS84Datum.INSTANCE);
127 datums.put("NAD83", GRS80Datum.INSTANCE);
128 datums.put("carthage", new ThreeParameterDatum(
129 "Carthage 1934 Tunisia", "carthage",
130 Ellipsoid.ClarkeIGN, -263.0, 6.0, 431.0));
131 datums.put("GGRS87", new ThreeParameterDatum(
132 "Greek Geodetic Reference System 1987", "GGRS87",
133 Ellipsoid.GRS80, -199.87, 74.79, 246.62));
134 datums.put("hermannskogel", new SevenParameterDatum(
135 "Hermannskogel", "hermannskogel",
136 Ellipsoid.Bessel1841, 577.326, 90.129, 463.919, 5.137, 1.474, 5.297, 2.4232));
137 datums.put("ire65", new SevenParameterDatum(
138 "Ireland 1965", "ire65",
139 Ellipsoid.AiryMod, 482.530, -130.596, 564.557, -1.042, -0.214, -0.631, 8.15));
140 datums.put("nzgd49", new SevenParameterDatum(
141 "New Zealand Geodetic Datum 1949", "nzgd49",
142 Ellipsoid.Hayford, 59.47, -5.04, 187.44, 0.47, -0.1, 1.024, -4.5993));
143 datums.put("OSGB36", new SevenParameterDatum(
144 "Airy 1830", "OSGB36",
145 Ellipsoid.Airy, 446.448, -125.157, 542.060, 0.1502, 0.2470, 0.8421, -20.4894));
146 datums.put("potsdam", new SevenParameterDatum(
147 "Potsdam Rauenberg 1950 DHDN", "potsdam",
148 Ellipsoid.Bessel1841, 598.1, 73.7, 418.2, 0.202, 0.045, -2.455, 6.7));
149
150 try {
151 inits = new LinkedHashMap<>();
152 for (ProjectionDefinition pd : loadProjectionDefinitions("resource://data/projection/custom-epsg")) {
153 inits.put(pd.code, pd);
154 loadNadgrids(pd.definition);
155 }
156 } catch (IOException ex) {
157 throw new JosmRuntimeException(ex);
158 }
159
160 for (ProjectionChoice pc : ProjectionPreference.getProjectionChoices()) {
161 for (String code : pc.allCodes()) {
162 allProjectionChoicesByCode.put(code, pc);
163 }
164 }
165 allCodes.addAll(inits.keySet());
166 allCodes.addAll(allProjectionChoicesByCode.keySet());
167 }
168
169 private Projections() {
170 // Hide default constructor for utils classes
171 }
172
173 private static void loadNadgrids(String definition) {
174 final String key = CustomProjection.Param.nadgrids.key;
175 if (definition.contains(key)) {
176 try {
177 String nadgridsId = CustomProjection.parseParameterList(definition, true).get(key);
178 if (nadgridsId.startsWith("@")) {
179 nadgridsId = nadgridsId.substring(1);
180 }
181 if (!"null".equals(nadgridsId) && !nadgrids.containsKey(nadgridsId)) {
182 nadgrids.put(nadgridsId, new NTV2GridShiftFileWrapper(nadgridsId));
183 }
184 } catch (ProjectionConfigurationException e) {
185 Logging.trace(e);
186 }
187 }
188 }
189
190 /**
191 * Convert from lat/lon to easting/northing using the current projection.
192 *
193 * @param ll the geographical point to convert (in WGS84 lat/lon)
194 * @return the corresponding east/north coordinates
195 * @since 12725
196 * @deprecated use <code>Main.getProjection().latlon2eastNorth(ll)</code>
197 */
198 @Deprecated
199 public static EastNorth project(ILatLon ll) {
200 if (ll == null) return null;
201 return Main.getProjection().latlon2eastNorth(ll);
202 }
203
204 /**
205 * Convert from lat/lon to easting/northing using the current projection.
206 *
207 * @param ll the geographical point to convert (in WGS84 lat/lon)
208 * @return the corresponding east/north coordinates
209 * @deprecated use <code>Main.getProjection().latlon2eastNorth(ll)</code>
210 */
211 @Deprecated
212 public static EastNorth project(LatLon ll) {
213 return project((ILatLon) ll);
214 }
215
216 /**
217 * Convert from easting/norting to lat/lon using the current projection.
218 *
219 * @param en the geographical point to convert (in projected coordinates)
220 * @return the corresponding lat/lon (WGS84)
221 * @deprecated use <code>Main.getProjection().eastNorth2latlon(en)</code>
222 */
223 @Deprecated
224 public static LatLon inverseProject(EastNorth en) {
225 if (en == null) return null;
226 return Main.getProjection().eastNorth2latlon(en);
227 }
228
229 /**
230 * Plugins can register additional base projections.
231 *
232 * @param id The "official" PROJ.4 id. In case the projection is not supported
233 * by PROJ.4, use some prefix, e.g. josm:myproj or gdal:otherproj.
234 * @param fac The base projection factory.
235 * @param origin Multiple plugins may implement the same base projection.
236 * Provide plugin name or similar string, so it be differentiated.
237 */
238 public static void registerBaseProjection(String id, ProjFactory fac, String origin) {
239 projs.put(id, fac);
240 }
241
242 public static void registerBaseProjection(String id, Class<? extends Proj> projClass, String origin) {
243 registerBaseProjection(id, new ClassProjFactory(projClass), origin);
244 }
245
246 /**
247 * Get a base projection by id.
248 *
249 * @param id the id, for example "lonlat" or "tmerc"
250 * @return the corresponding base projection if the id is known, null otherwise
251 */
252 public static Proj getBaseProjection(String id) {
253 ProjFactory fac = projs.get(id);
254 if (fac == null) return null;
255 return fac.createInstance();
256 }
257
258 /**
259 * Get an ellipsoid by id.
260 *
261 * @param id the id, for example "bessel" or "WGS84"
262 * @return the corresponding ellipsoid if the id is known, null otherwise
263 */
264 public static Ellipsoid getEllipsoid(String id) {
265 return ellipsoids.get(id);
266 }
267
268 /**
269 * Get a geodetic datum by id.
270 *
271 * @param id the id, for example "potsdam" or "WGS84"
272 * @return the corresponding datum if the id is known, null otherwise
273 */
274 public static Datum getDatum(String id) {
275 return datums.get(id);
276 }
277
278 /**
279 * Get a NTV2 grid database by id.
280 * @param id the id
281 * @return the corresponding NTV2 grid if the id is known, null otherwise
282 */
283 public static NTV2GridShiftFileWrapper getNTV2Grid(String id) {
284 return nadgrids.get(id);
285 }
286
287 /**
288 * Get the projection definition string for the given code.
289 * @param code the code
290 * @return the string that can be processed by #{link CustomProjection}.
291 * Null, if the code isn't supported.
292 */
293 public static String getInit(String code) {
294 ProjectionDefinition pd = inits.get(code.toUpperCase(Locale.ENGLISH));
295 if (pd == null) return null;
296 return pd.definition;
297 }
298
299 /**
300 * Load projection definitions from file.
301 *
302 * @param path the path
303 * @return projection definitions
304 * @throws IOException in case of I/O error
305 */
306 public static List<ProjectionDefinition> loadProjectionDefinitions(String path) throws IOException {
307 try (
308 CachedFile cf = new CachedFile(path);
309 BufferedReader r = cf.getContentReader()
310 ) {
311 return loadProjectionDefinitions(r);
312 }
313 }
314
315 /**
316 * Load projection definitions from file.
317 *
318 * @param r the reader
319 * @return projection definitions
320 * @throws IOException in case of I/O error
321 */
322 public static List<ProjectionDefinition> loadProjectionDefinitions(BufferedReader r) throws IOException {
323 List<ProjectionDefinition> result = new ArrayList<>();
324 Pattern epsgPattern = Pattern.compile("<(\\d+)>(.*)<>");
325 String line, lastline = "";
326 while ((line = r.readLine()) != null) {
327 line = line.trim();
328 if (!line.startsWith("#") && !line.isEmpty()) {
329 if (!lastline.startsWith("#")) throw new AssertionError("EPSG file seems corrupted");
330 String name = lastline.substring(1).trim();
331 Matcher m = epsgPattern.matcher(line);
332 if (m.matches()) {
333 String code = "EPSG:" + m.group(1);
334 String definition = m.group(2).trim();
335 result.add(new ProjectionDefinition(code, name, definition));
336 } else {
337 Logging.warn("Failed to parse line from the EPSG projection definition: "+line);
338 }
339 }
340 lastline = line;
341 }
342 return result;
343 }
344
345 /**
346 * Get a projection by code.
347 * @param code the code, e.g. "EPSG:2026"
348 * @return the corresponding projection, if the code is known, null otherwise
349 */
350 public static Projection getProjectionByCode(String code) {
351 Projection proj = projectionsByCode_cache.get(code);
352 if (proj != null) return proj;
353 ProjectionChoice pc = allProjectionChoicesByCode.get(code);
354 if (pc != null) {
355 Collection<String> pref = pc.getPreferencesFromCode(code);
356 pc.setPreferences(pref);
357 try {
358 proj = pc.getProjection();
359 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
360 Logging.log(Logging.LEVEL_WARN, "Unable to get projection "+code+" with "+pc+':', e);
361 }
362 }
363 if (proj == null) {
364 ProjectionDefinition pd = inits.get(code);
365 if (pd == null) return null;
366 proj = new CustomProjection(pd.name, code, pd.definition);
367 }
368 projectionsByCode_cache.put(code, proj);
369 return proj;
370 }
371
372 /**
373 * Get a list of all supported projection codes.
374 *
375 * @return all supported projection codes
376 * @see #getProjectionByCode(java.lang.String)
377 */
378 public static Collection<String> getAllProjectionCodes() {
379 return Collections.unmodifiableCollection(allCodes);
380 }
381
382 /**
383 * Get a list of ids of all registered base projections.
384 *
385 * @return all registered base projection ids
386 * @see #getBaseProjection(java.lang.String)
387 */
388 public static Collection<String> getAllBaseProjectionIds() {
389 return projs.keySet();
390 }
391
392 private static String listKeys(Map<String, ?> map) {
393 List<String> keys = new ArrayList<>(map.keySet());
394 Collections.sort(keys);
395 return Utils.join(", ", keys);
396 }
397
398 /**
399 * Replies the list of projections as string (comma separated).
400 * @return the list of projections as string (comma separated)
401 * @since 8533
402 */
403 public static String listProjs() {
404 return listKeys(projs);
405 }
406
407 /**
408 * Replies the list of ellipsoids as string (comma separated).
409 * @return the list of ellipsoids as string (comma separated)
410 * @since 8533
411 */
412 public static String listEllipsoids() {
413 return listKeys(ellipsoids);
414 }
415
416 /**
417 * Replies the list of datums as string (comma separated).
418 * @return the list of datums as string (comma separated)
419 * @since 8533
420 */
421 public static String listDatums() {
422 return listKeys(datums);
423 }
424
425 /**
426 * Replies the list of nadgrids as string (comma separated).
427 * @return the list of nadgrids as string (comma separated)
428 * @since 8533
429 */
430 public static String listNadgrids() {
431 return listKeys(nadgrids);
432 }
433}
Note: See TracBrowser for help on using the repository browser.