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