toText method
The MGRS grid reference string representation with components separated by whitespace by default.
To distinguish from civilian UTM coordinate representations, no space is included within the zone/band grid zone designator.
Components are separated by spaces by default. For a military-style
unseparated string set militaryStyle to true.
If zeroPadZone is true, then all zone numbers (1..60) are formatted with
two digits, e.g. 31 or 04. By default only significant digits are
formatted, e.g. 31 or 4.
Note that MGRS grid references get truncated, not rounded (unlike UTM coordinates); grid references indicate a bounding square, rather than a point, with the size of the square indicated by the precision - a precision of 10 indicates a 1-metre square, a precision of 4 indicates a 1,000-metre square (hence 31U DQ 48 11 indicates a 1km square with SW corner at 31 N 448000 5411000, which would include the 1m square 31U DQ 48251 11932).
Examples:
// a sample MGRS reference `31U DQ 48251 11932`
final mgrsRef = Mgrs(31, 'U', 'D', 'Q', 48251, 11932);
// 10 digits, the precision level 1 m
print(mgrsRef.toText()); // '31U DQ 48251 11932'
// 8 digits, the precision level 10 m
print(mgrsRef.toText(digits: 8)); // '31U DQ 4825 1193'
// 4 digits, the precision level 1 km
print(mgrsRef.toText(digits: 4)); // '31U DQ 48 11'
// 4 digits, the precision level 1 km, military style
print(mgrsRef.toText(digits: 4, militaryStyle: true)); // '31UDQ4811'
// another sample `4Q FJ 02345 07890`
final mgrsRef2 = Mgrs.parse('4Q FJ 02345 07890');
// zone without a leading zero, 10 digits
print(mgrsRef2.toText()); // '4Q FJ 02345 07890'
// zone with a leading zero, 10 digits
print(mgrsRef2.toText(zeroPadZone: true)); // '04Q FJ 02345 07890'
Implementation
String toText({
int digits = 10,
bool militaryStyle = false,
bool zeroPadZone = false,
}) {
if (!(digits == 2 ||
digits == 4 ||
digits == 6 ||
digits == 8 ||
digits == 10)) {
throw FormatException('invalid precision `$digits`');
}
final lonZone = gridSquare.lonZone;
final band = gridSquare.band;
final column = gridSquare.column;
final row = gridSquare.row;
// truncate to required precision
final digitsPer2 = digits ~/ 2;
final eRounded =
digitsPer2 == 5 ? easting : (easting / pow(10, 5 - digitsPer2)).floor();
final nRounded = digitsPer2 == 5
? northing
: (northing / pow(10, 5 - digitsPer2)).floor();
// ensure leading zeros on zone if `zeroPadZone` is set true
final zPadded =
zeroPadZone ? lonZone.toString().padLeft(2, '0') : lonZone.toString();
// ensure leading zeros on easting and northing when needed
final ePadded = eRounded.toString().padLeft(digitsPer2, '0');
final nPadded = nRounded.toString().padLeft(digitsPer2, '0');
return militaryStyle
? '$zPadded$band$column$row$ePadded$nPadded'
: '$zPadded$band $column$row $ePadded $nPadded';
}