GeographicLib  1.36
MGRS.hpp
Go to the documentation of this file.
1 /**
2  * \file MGRS.hpp
3  * \brief Header for GeographicLib::MGRS class
4  *
5  * Copyright (c) Charles Karney (2008-2011) <charles@karney.com> and licensed
6  * under the MIT/X11 License. For more information, see
7  * http://geographiclib.sourceforge.net/
8  **********************************************************************/
9 
10 #if !defined(GEOGRAPHICLIB_MGRS_HPP)
11 #define GEOGRAPHICLIB_MGRS_HPP 1
12 
14 #include <GeographicLib/UTMUPS.hpp>
15 
16 #if defined(_MSC_VER)
17 // Squelch warnings about dll vs string
18 # pragma warning (push)
19 # pragma warning (disable: 4251)
20 #endif
21 
22 namespace GeographicLib {
23 
24  /**
25  * \brief Convert between UTM/UPS and %MGRS
26  *
27  * MGRS is defined in Chapter 3 of
28  * - J. W. Hager, L. L. Fry, S. S. Jacks, D. R. Hill,
29  * <a href="http://earth-info.nga.mil/GandG/publications/tm8358.1/pdf/TM8358_1.pdf">
30  * Datums, Ellipsoids, Grids, and Grid Reference Systems</a>,
31  * Defense Mapping Agency, Technical Manual TM8358.1 (1990).
32  * .
33  * This document has been updated by the two NGA documents
34  * - <a href="https://nsgreg.nga.mil/doc/view?i=4057"> Universal Grids and
35  * Grid Reference Systems</a>, NGA.STND.0037_2.0.0_GRIDS (2014).
36  * - <a href="https://nsgreg.nga.mil/doc/view?i=4056"> The Universal Grids
37  * and the Transverse Mercator and Polar Stereographic Map Projections</a>,
38  * NGA.SIG.0012_2.0.0_UTMUPS (2014).
39  *
40  * This implementation has the following properties:
41  * - The conversions are closed, i.e., output from Forward is legal input for
42  * Reverse and vice versa. Conversion in both directions preserve the
43  * UTM/UPS selection and the UTM zone.
44  * - Forward followed by Reverse and vice versa is approximately the
45  * identity. (This is affected in predictable ways by errors in
46  * determining the latitude band and by loss of precision in the MGRS
47  * coordinates.)
48  * - All MGRS coordinates truncate to legal 100 km blocks. All MGRS
49  * coordinates with a legal 100 km block prefix are legal (even though the
50  * latitude band letter may now belong to a neighboring band).
51  * - The range of UTM/UPS coordinates allowed for conversion to MGRS
52  * coordinates is the maximum consistent with staying within the letter
53  * ranges of the MGRS scheme.
54  * - All the transformations are implemented as static methods in the MGRS
55  * class.
56  *
57  * The <a href="http://www.nga.mil">NGA</a> software package
58  * <a href="http://earth-info.nga.mil/GandG/geotrans/index.html">geotrans</a>
59  * also provides conversions to and from MGRS. Version 3.0 (and earlier)
60  * suffers from some drawbacks:
61  * - Inconsistent rules are used to determine the whether a particular MGRS
62  * coordinate is legal. A more systematic approach is taken here.
63  * - The underlying projections are not very accurately implemented.
64  *
65  * Example of use:
66  * \include example-MGRS.cpp
67  **********************************************************************/
69  private:
70  typedef Math::real real;
71  // The smallest length s.t., 1.0e7 - eps_ < 1.0e7 (approx 1.9 nm)
72  static const real eps_;
73  // The smallest angle s.t., 90 - eps_ < 90 (approx 50e-12 arcsec)
74  static const real angeps_;
75  static const std::string hemispheres_;
76  static const std::string utmcols_[3];
77  static const std::string utmrow_;
78  static const std::string upscols_[4];
79  static const std::string upsrows_[2];
80  static const std::string latband_;
81  static const std::string upsband_;
82  static const std::string digits_;
83 
84  static const int mineasting_[4];
85  static const int maxeasting_[4];
86  static const int minnorthing_[4];
87  static const int maxnorthing_[4];
88  enum {
89  base_ = 10,
90  // Top-level tiles are 10^5 m = 100 km on a side
91  tilelevel_ = 5,
92  // Period of UTM row letters
93  utmrowperiod_ = 20,
94  // Row letters are shifted by 5 for even zones
95  utmevenrowshift_ = 5,
96  // Maximum precision is um
97  maxprec_ = 5 + 6,
98  };
99  static void CheckCoords(bool utmp, bool& northp, real& x, real& y);
100  static int UTMRow(int iband, int icol, int irow);
101 
102  friend class UTMUPS; // UTMUPS::StandardZone calls LatitudeBand
103  // Return latitude band number [-10, 10) for the given latitude (degrees).
104  // The bands are reckoned in include their southern edges.
105  static int LatitudeBand(real lat) {
106  int ilat = int(std::floor(lat));
107  return (std::max)(-10, (std::min)(9, (ilat + 80)/8 - 10));
108  }
109  // Return approximate latitude band number [-10, 10) for the given northing
110  // (meters). With this rule, each 100km tile would have a unique band
111  // letter corresponding to the latitude at the center of the tile. This
112  // function isn't currently used.
113  static int ApproxLatitudeBand(real y) {
114  // northing at tile center in units of tile = 100km
115  real ya = std::floor( (std::min)(real(88), std::abs(y/tile_)) ) +
116  real(0.5);
117  // convert to lat (mult by 90/100) and then to band (divide by 8)
118  // the +1 fine tunes the boundary between bands 3 and 4
119  int b = int(std::floor( ((ya * 9 + 1) / 10) / 8 ));
120  // For the northern hemisphere we have
121  // band rows num
122  // N 0 0:8 9
123  // P 1 9:17 9
124  // Q 2 18:26 9
125  // R 3 27:34 8
126  // S 4 35:43 9
127  // T 5 44:52 9
128  // U 6 53:61 9
129  // V 7 62:70 9
130  // W 8 71:79 9
131  // X 9 80:94 15
132  return y >= 0 ? b : -(b + 1);
133  }
134  // UTMUPS access these enums
135  enum {
136  tile_ = 100000, // Size MGRS blocks
137  minutmcol_ = 1,
138  maxutmcol_ = 9,
139  minutmSrow_ = 10,
140  maxutmSrow_ = 100, // Also used for UTM S false northing
141  minutmNrow_ = 0, // Also used for UTM N false northing
142  maxutmNrow_ = 95,
143  minupsSind_ = 8, // These 4 ind's apply to easting and northing
144  maxupsSind_ = 32,
145  minupsNind_ = 13,
146  maxupsNind_ = 27,
147  upseasting_ = 20, // Also used for UPS false northing
148  utmeasting_ = 5, // UTM false easting
149  // Difference between S hemisphere northing and N hemisphere northing
150  utmNshift_ = (maxutmSrow_ - minutmNrow_) * tile_
151  };
152  MGRS(); // Disable constructor
153 
154  public:
155 
156  /**
157  * Convert UTM or UPS coordinate to an MGRS coordinate.
158  *
159  * @param[in] zone UTM zone (zero means UPS).
160  * @param[in] northp hemisphere (true means north, false means south).
161  * @param[in] x easting of point (meters).
162  * @param[in] y northing of point (meters).
163  * @param[in] prec precision relative to 100 km.
164  * @param[out] mgrs MGRS string.
165  * @exception GeographicErr if \e zone, \e x, or \e y is outside its
166  * allowed range.
167  * @exception GeographicErr if the memory for the MGRS string can't be
168  * allocated.
169  *
170  * \e prec specifies the precision of the MGRS string as follows:
171  * - prec = &minus;1 (min), only the grid zone is returned
172  * - prec = 0 (min), 100 km
173  * - prec = 1, 10 km
174  * - prec = 2, 1 km
175  * - prec = 3, 100 m
176  * - prec = 4, 10 m
177  * - prec = 5, 1 m
178  * - prec = 6, 0.1 m
179  * - prec = 11 (max), 1 &mu;m
180  *
181  * UTM eastings are allowed to be in the range [100 km, 900 km], northings
182  * are allowed to be in in [0 km, 9500 km] for the northern hemisphere and
183  * in [1000 km, 10000 km] for the southern hemisphere. (However UTM
184  * northings can be continued across the equator. So the actual limits on
185  * the northings are [&minus;9000 km, 9500 km] for the "northern"
186  * hemisphere and [1000 km, 19500 km] for the "southern" hemisphere.)
187  *
188  * UPS eastings/northings are allowed to be in the range [1300 km, 2700 km]
189  * in the northern hemisphere and in [800 km, 3200 km] in the southern
190  * hemisphere.
191  *
192  * The ranges are 100 km more restrictive that for the conversion between
193  * geographic coordinates and UTM and UPS given by UTMUPS. These
194  * restrictions are dictated by the allowed letters in MGRS coordinates.
195  * The choice of 9500 km for the maximum northing for northern hemisphere
196  * and of 1000 km as the minimum northing for southern hemisphere provide
197  * at least 0.5 degree extension into standard UPS zones. The upper ends
198  * of the ranges for the UPS coordinates is dictated by requiring symmetry
199  * about the meridians 0E and 90E.
200  *
201  * All allowed UTM and UPS coordinates may now be converted to legal MGRS
202  * coordinates with the proviso that eastings and northings on the upper
203  * boundaries are silently reduced by about 4 nm (4 nanometers) to place
204  * them \e within the allowed range. (This includes reducing a southern
205  * hemisphere northing of 10000 km by 4 nm so that it is placed in latitude
206  * band M.) The UTM or UPS coordinates are truncated to requested
207  * precision to determine the MGRS coordinate. Thus in UTM zone 38n, the
208  * square area with easting in [444 km, 445 km) and northing in [3688 km,
209  * 3689 km) maps to MGRS coordinate 38SMB4488 (at \e prec = 2, 1 km),
210  * Khulani Sq., Baghdad.
211  *
212  * The UTM/UPS selection and the UTM zone is preserved in the conversion to
213  * MGRS coordinate. Thus for \e zone > 0, the MGRS coordinate begins with
214  * the zone number followed by one of [C--M] for the southern
215  * hemisphere and [N--X] for the northern hemisphere. For \e zone =
216  * 0, the MGRS coordinates begins with one of [AB] for the southern
217  * hemisphere and [XY] for the northern hemisphere.
218  *
219  * The conversion to the MGRS is exact for prec in [0, 5] except that a
220  * neighboring latitude band letter may be given if the point is within 5nm
221  * of a band boundary. For prec in [6, 11], the conversion is accurate to
222  * roundoff.
223  *
224  * If \e prec = -1, then the "grid zone designation", e.g., 18T, is
225  * returned. This consists of the UTM zone number (absent for UPS) and the
226  * first letter of the MGRS string which labels the latitude band for UTM
227  * and the hemisphere for UPS.
228  *
229  * If \e x or \e y is NaN or if \e zone is UTMUPS::INVALID, the returned
230  * MGRS string is "INVALID".
231  *
232  * Return the result via a reference argument to avoid the overhead of
233  * allocating a potentially large number of small strings. If an error is
234  * thrown, then \e mgrs is unchanged.
235  **********************************************************************/
236  static void Forward(int zone, bool northp, real x, real y,
237  int prec, std::string& mgrs);
238 
239  /**
240  * Convert UTM or UPS coordinate to an MGRS coordinate when the latitude is
241  * known.
242  *
243  * @param[in] zone UTM zone (zero means UPS).
244  * @param[in] northp hemisphere (true means north, false means south).
245  * @param[in] x easting of point (meters).
246  * @param[in] y northing of point (meters).
247  * @param[in] lat latitude (degrees).
248  * @param[in] prec precision relative to 100 km.
249  * @param[out] mgrs MGRS string.
250  * @exception GeographicErr if \e zone, \e x, or \e y is outside its
251  * allowed range.
252  * @exception GeographicErr if \e lat is inconsistent with the given UTM
253  * coordinates.
254  * @exception std::bad_alloc if the memory for \e mgrs can't be allocated.
255  *
256  * The latitude is ignored for \e zone = 0 (UPS); otherwise the latitude is
257  * used to determine the latitude band and this is checked for consistency
258  * using the same tests as Reverse.
259  **********************************************************************/
260  static void Forward(int zone, bool northp, real x, real y, real lat,
261  int prec, std::string& mgrs);
262 
263  /**
264  * Convert a MGRS coordinate to UTM or UPS coordinates.
265  *
266  * @param[in] mgrs MGRS string.
267  * @param[out] zone UTM zone (zero means UPS).
268  * @param[out] northp hemisphere (true means north, false means south).
269  * @param[out] x easting of point (meters).
270  * @param[out] y northing of point (meters).
271  * @param[out] prec precision relative to 100 km.
272  * @param[in] centerp if true (default), return center of the MGRS square,
273  * else return SW (lower left) corner.
274  * @exception GeographicErr if \e mgrs is illegal.
275  *
276  * All conversions from MGRS to UTM/UPS are permitted provided the MGRS
277  * coordinate is a possible result of a conversion in the other direction.
278  * (The leading 0 may be dropped from an input MGRS coordinate for UTM
279  * zones 1--9.) In addition, MGRS coordinates with a neighboring
280  * latitude band letter are permitted provided that some portion of the
281  * 100 km block is within the given latitude band. Thus
282  * - 38VLS and 38WLS are allowed (latitude 64N intersects the square
283  * 38[VW]LS); but 38VMS is not permitted (all of 38VMS is north of 64N)
284  * - 38MPE and 38NPF are permitted (they straddle the equator); but 38NPE
285  * and 38MPF are not permitted (the equator does not intersect either
286  * block).
287  * - Similarly ZAB and YZB are permitted (they straddle the prime
288  * meridian); but YAB and ZZB are not (the prime meridian does not
289  * intersect either block).
290  *
291  * The UTM/UPS selection and the UTM zone is preserved in the conversion
292  * from MGRS coordinate. The conversion is exact for prec in [0, 5]. With
293  * centerp = true the conversion from MGRS to geographic and back is
294  * stable. This is not assured if \e centerp = false.
295  *
296  * If a "grid zone designation" (for example, 18T or A) is given, then some
297  * suitable (but essentially arbitrary) point within that grid zone is
298  * returned. The main utility of the conversion is to allow \e zone and \e
299  * northp to be determined. In this case, the \e centerp parameter is
300  * ignored.
301  *
302  * If the first 3 characters of \e mgrs are "INV", then \e x and \e y are
303  * set to NaN and \e zone is set to UTMUPS::INVALID.
304  *
305  * If an exception is thrown, then the arguments are unchanged.
306  **********************************************************************/
307  static void Reverse(const std::string& mgrs,
308  int& zone, bool& northp, real& x, real& y,
309  int& prec, bool centerp = true);
310 
311  /** \name Inspector functions
312  **********************************************************************/
313  ///@{
314  /**
315  * @return \e a the equatorial radius of the WGS84 ellipsoid (meters).
316  *
317  * (The WGS84 value is returned because the UTM and UPS projections are
318  * based on this ellipsoid.)
319  **********************************************************************/
321 
322  /**
323  * @return \e f the flattening of the WGS84 ellipsoid.
324  *
325  * (The WGS84 value is returned because the UTM and UPS projections are
326  * based on this ellipsoid.)
327  **********************************************************************/
328  static Math::real Flattening() { return UTMUPS::Flattening(); }
329  ///@}
330 
331  /// \cond SKIP
332  /**
333  * <b>DEPRECATED</b>
334  * @return \e r the inverse flattening of the WGS84 ellipsoid.
335  **********************************************************************/
336  static Math::real InverseFlattening()
337  { return UTMUPS::InverseFlattening(); }
338  /// \endcond
339  };
340 
341 } // namespace GeographicLib
342 
343 #if defined(_MSC_VER)
344 # pragma warning (pop)
345 #endif
346 
347 #endif // GEOGRAPHICLIB_MGRS_HPP