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

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

see #15229 - deprecate ILatLon#getEastNorth() so ILatLon has no dependency on Main.proj

  • Property svn:eol-style set to native
File size: 16.5 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 */
197 public static EastNorth project(ILatLon ll) {
198 if (ll == null) return null;
199 return Main.getProjection().latlon2eastNorth(ll);
200 }
201
202 /**
203 * Convert from lat/lon to easting/northing using the current projection.
204 *
205 * @param ll the geographical point to convert (in WGS84 lat/lon)
206 * @return the corresponding east/north coordinates
207 */
208 public static EastNorth project(LatLon ll) {
209 return project((ILatLon) ll);
210 }
211
212 /**
213 * Convert from easting/norting to lat/lon using the current projection.
214 *
215 * @param en the geographical point to convert (in projected coordinates)
216 * @return the corresponding lat/lon (WGS84)
217 */
218 public static LatLon inverseProject(EastNorth en) {
219 if (en == null) return null;
220 return Main.getProjection().eastNorth2latlon(en);
221 }
222
223 /**
224 * Plugins can register additional base projections.
225 *
226 * @param id The "official" PROJ.4 id. In case the projection is not supported
227 * by PROJ.4, use some prefix, e.g. josm:myproj or gdal:otherproj.
228 * @param fac The base projection factory.
229 * @param origin Multiple plugins may implement the same base projection.
230 * Provide plugin name or similar string, so it be differentiated.
231 */
232 public static void registerBaseProjection(String id, ProjFactory fac, String origin) {
233 projs.put(id, fac);
234 }
235
236 public static void registerBaseProjection(String id, Class<? extends Proj> projClass, String origin) {
237 registerBaseProjection(id, new ClassProjFactory(projClass), origin);
238 }
239
240 /**
241 * Get a base projection by id.
242 *
243 * @param id the id, for example "lonlat" or "tmerc"
244 * @return the corresponding base projection if the id is known, null otherwise
245 */
246 public static Proj getBaseProjection(String id) {
247 ProjFactory fac = projs.get(id);
248 if (fac == null) return null;
249 return fac.createInstance();
250 }
251
252 /**
253 * Get an ellipsoid by id.
254 *
255 * @param id the id, for example "bessel" or "WGS84"
256 * @return the corresponding ellipsoid if the id is known, null otherwise
257 */
258 public static Ellipsoid getEllipsoid(String id) {
259 return ellipsoids.get(id);
260 }
261
262 /**
263 * Get a geodetic datum by id.
264 *
265 * @param id the id, for example "potsdam" or "WGS84"
266 * @return the corresponding datum if the id is known, null otherwise
267 */
268 public static Datum getDatum(String id) {
269 return datums.get(id);
270 }
271
272 /**
273 * Get a NTV2 grid database by id.
274 * @param id the id
275 * @return the corresponding NTV2 grid if the id is known, null otherwise
276 */
277 public static NTV2GridShiftFileWrapper getNTV2Grid(String id) {
278 return nadgrids.get(id);
279 }
280
281 /**
282 * Get the projection definition string for the given code.
283 * @param code the code
284 * @return the string that can be processed by #{link CustomProjection}.
285 * Null, if the code isn't supported.
286 */
287 public static String getInit(String code) {
288 ProjectionDefinition pd = inits.get(code.toUpperCase(Locale.ENGLISH));
289 if (pd == null) return null;
290 return pd.definition;
291 }
292
293 /**
294 * Load projection definitions from file.
295 *
296 * @param path the path
297 * @return projection definitions
298 * @throws IOException in case of I/O error
299 */
300 public static List<ProjectionDefinition> loadProjectionDefinitions(String path) throws IOException {
301 try (
302 CachedFile cf = new CachedFile(path);
303 BufferedReader r = cf.getContentReader()
304 ) {
305 return loadProjectionDefinitions(r);
306 }
307 }
308
309 /**
310 * Load projection definitions from file.
311 *
312 * @param r the reader
313 * @return projection definitions
314 * @throws IOException in case of I/O error
315 */
316 public static List<ProjectionDefinition> loadProjectionDefinitions(BufferedReader r) throws IOException {
317 List<ProjectionDefinition> result = new ArrayList<>();
318 Pattern epsgPattern = Pattern.compile("<(\\d+)>(.*)<>");
319 String line, lastline = "";
320 while ((line = r.readLine()) != null) {
321 line = line.trim();
322 if (!line.startsWith("#") && !line.isEmpty()) {
323 if (!lastline.startsWith("#")) throw new AssertionError("EPSG file seems corrupted");
324 String name = lastline.substring(1).trim();
325 Matcher m = epsgPattern.matcher(line);
326 if (m.matches()) {
327 String code = "EPSG:" + m.group(1);
328 String definition = m.group(2).trim();
329 result.add(new ProjectionDefinition(code, name, definition));
330 } else {
331 Logging.warn("Failed to parse line from the EPSG projection definition: "+line);
332 }
333 }
334 lastline = line;
335 }
336 return result;
337 }
338
339 /**
340 * Get a projection by code.
341 * @param code the code, e.g. "EPSG:2026"
342 * @return the corresponding projection, if the code is known, null otherwise
343 */
344 public static Projection getProjectionByCode(String code) {
345 Projection proj = projectionsByCode_cache.get(code);
346 if (proj != null) return proj;
347 ProjectionChoice pc = allProjectionChoicesByCode.get(code);
348 if (pc != null) {
349 Collection<String> pref = pc.getPreferencesFromCode(code);
350 pc.setPreferences(pref);
351 try {
352 proj = pc.getProjection();
353 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
354 Logging.log(Logging.LEVEL_WARN, "Unable to get projection "+code+" with "+pc+':', e);
355 }
356 }
357 if (proj == null) {
358 ProjectionDefinition pd = inits.get(code);
359 if (pd == null) return null;
360 proj = new CustomProjection(pd.name, code, pd.definition);
361 }
362 projectionsByCode_cache.put(code, proj);
363 return proj;
364 }
365
366 /**
367 * Get a list of all supported projection codes.
368 *
369 * @return all supported projection codes
370 * @see #getProjectionByCode(java.lang.String)
371 */
372 public static Collection<String> getAllProjectionCodes() {
373 return Collections.unmodifiableCollection(allCodes);
374 }
375
376 /**
377 * Get a list of ids of all registered base projections.
378 *
379 * @return all registered base projection ids
380 * @see #getBaseProjection(java.lang.String)
381 */
382 public static Collection<String> getAllBaseProjectionIds() {
383 return projs.keySet();
384 }
385
386 private static String listKeys(Map<String, ?> map) {
387 List<String> keys = new ArrayList<>(map.keySet());
388 Collections.sort(keys);
389 return Utils.join(", ", keys);
390 }
391
392 /**
393 * Replies the list of projections as string (comma separated).
394 * @return the list of projections as string (comma separated)
395 * @since 8533
396 */
397 public static String listProjs() {
398 return listKeys(projs);
399 }
400
401 /**
402 * Replies the list of ellipsoids as string (comma separated).
403 * @return the list of ellipsoids as string (comma separated)
404 * @since 8533
405 */
406 public static String listEllipsoids() {
407 return listKeys(ellipsoids);
408 }
409
410 /**
411 * Replies the list of datums as string (comma separated).
412 * @return the list of datums as string (comma separated)
413 * @since 8533
414 */
415 public static String listDatums() {
416 return listKeys(datums);
417 }
418
419 /**
420 * Replies the list of nadgrids as string (comma separated).
421 * @return the list of nadgrids as string (comma separated)
422 * @since 8533
423 */
424 public static String listNadgrids() {
425 return listKeys(nadgrids);
426 }
427}
Note: See TracBrowser for help on using the repository browser.