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