1 package tim.prune.data;
3 import java.text.DecimalFormat;
4 import java.text.NumberFormat;
5 import java.util.Locale;
8 * Class to represent a lat/long coordinate
9 * and provide conversion functions
11 public abstract class Coordinate
13 public static final int NO_CARDINAL = -1;
14 public static final int NORTH = 0;
15 public static final int EAST = 1;
16 public static final int SOUTH = 2;
17 public static final int WEST = 3;
18 private static final char[] PRINTABLE_CARDINALS = {'N', 'E', 'S', 'W'};
19 public static final int FORMAT_DEG_MIN_SEC = 10;
20 public static final int FORMAT_DEG_MIN = 11;
21 public static final int FORMAT_DEG = 12;
22 public static final int FORMAT_DEG_WITHOUT_CARDINAL = 13;
23 public static final int FORMAT_DEG_WHOLE_MIN = 14;
24 public static final int FORMAT_DEG_MIN_SEC_WITH_SPACES = 15;
25 public static final int FORMAT_CARDINAL = 16;
26 public static final int FORMAT_DECIMAL_FORCE_POINT = 17;
27 public static final int FORMAT_NONE = 19;
29 /** Number formatter for fixed decimals with forced decimal point */
30 private static final NumberFormat EIGHT_DP = NumberFormat.getNumberInstance(Locale.UK);
31 // Select the UK locale for this formatter so that decimal point is always used (not comma)
33 if (EIGHT_DP instanceof DecimalFormat) ((DecimalFormat) EIGHT_DP).applyPattern("0.00000000");
35 /** Number formatter for fixed decimals with forced decimal point */
36 private static final NumberFormat FIVE_DP = NumberFormat.getNumberInstance(Locale.UK);
38 if (FIVE_DP instanceof DecimalFormat) ((DecimalFormat) FIVE_DP).applyPattern("0.00000");
42 private boolean _valid = false;
43 private boolean _cardinalGuessed = false;
44 protected int _cardinal = NORTH;
45 private int _degrees = 0;
46 private int _minutes = 0;
47 private int _seconds = 0;
48 private int _fracs = 0;
49 private int _fracDenom = 0;
50 private String _originalString = null;
51 private int _originalFormat = FORMAT_NONE;
52 private double _asDouble = 0.0;
56 * Constructor given String
57 * @param inString string to parse
59 public Coordinate(String inString)
61 _originalString = inString;
65 inString = inString.trim();
66 strLen = inString.length();
70 // Check for cardinal character either at beginning or end
71 boolean hasCardinal = true;
72 _cardinal = getCardinal(inString.charAt(0), inString.charAt(strLen-1));
73 if (_cardinal == NO_CARDINAL) {
75 // use default from concrete subclass
76 _cardinal = getDefaultCardinal();
77 _cardinalGuessed = true;
79 else if (isJustNumber(inString)) {
82 _cardinalGuessed = true;
85 // count numeric fields - 1=d, 2=dm, 3=dm.m/dms, 4=dms.s
87 boolean isNumeric = false;
89 long[] fields = new long[4]; // needs to be long for lengthy decimals
90 long[] denoms = new long[4];
91 boolean[] otherDelims = new boolean[5]; // remember whether delimiters have non-decimal chars
94 // Loop over characters in input string, populating fields array
95 for (int i=0; i<strLen; i++)
97 currChar = inString.charAt(i);
98 if (currChar >= '0' && currChar <= '9')
104 denoms[numFields-1] = 1;
106 if (denoms[numFields-1] < 1E18) // ignore trailing characters if too big for long
108 fields[numFields-1] = fields[numFields-1] * 10 + (currChar - '0');
109 denoms[numFields-1] *= 10;
115 // Remember delimiters
116 if (currChar != ',' && currChar != '.') {otherDelims[numFields] = true;}
119 _valid = (numFields > 0);
121 catch (ArrayIndexOutOfBoundsException obe)
123 // more than four fields found - unable to parse
126 // parse fields according to number found
127 _degrees = (int) fields[0];
128 _asDouble = _degrees;
129 _originalFormat = hasCardinal?FORMAT_DEG:FORMAT_DEG_WITHOUT_CARDINAL;
135 // String is just decimal degrees
136 double numMins = fields[1] * 60.0 / denoms[1];
137 _minutes = (int) numMins;
138 double numSecs = (numMins - _minutes) * 60.0;
139 _seconds = (int) numSecs;
140 _fracs = (int) ((numSecs - _seconds) * 10);
141 _asDouble = _degrees + 1.0 * fields[1] / denoms[1];
145 // String is degrees and minutes (due to non-decimal separator)
146 _originalFormat = FORMAT_DEG_MIN;
147 _minutes = (int) fields[1];
150 _asDouble = 1.0 * _degrees + (_minutes / 60.0);
153 // Differentiate between d-m.f and d-m-s using . or ,
154 else if (numFields == 3 && !otherDelims[2])
156 // String is degrees-minutes.fractions
157 _originalFormat = FORMAT_DEG_MIN;
158 _minutes = (int) fields[1];
159 double numSecs = fields[2] * 60.0 / denoms[2];
160 _seconds = (int) numSecs;
161 _fracs = (int) ((numSecs - _seconds) * 10);
162 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (numSecs / 3600.0);
164 else if (numFields == 4 || numFields == 3)
166 // String is degrees-minutes-seconds.fractions
167 _originalFormat = FORMAT_DEG_MIN_SEC;
168 _minutes = (int) fields[1];
169 _seconds = (int) fields[2];
170 _fracs = (int) fields[3];
171 _fracDenom = (int) denoms[3];
172 if (_fracDenom < 1) {_fracDenom = 1;}
173 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (_seconds / 3600.0) + (_fracs / 3600.0 / _fracDenom);
175 if (_cardinal == WEST || _cardinal == SOUTH || inString.charAt(0) == '-')
176 _asDouble = -_asDouble;
178 _valid = _valid && (_degrees <= getMaxDegrees() && _minutes < 60 && _seconds < 60 && _fracs < _fracDenom)
179 && Math.abs(_asDouble) <= getMaxDegrees();
186 * Get the cardinal from the given character
187 * @param inFirstChar first character from file
188 * @param inLastChar last character from file
190 protected int getCardinal(char inFirstChar, char inLastChar)
192 // Try leading character first
193 int cardinal = getCardinal(inFirstChar);
194 // if not there, try trailing character
195 if (cardinal == NO_CARDINAL) {
196 cardinal = getCardinal(inLastChar);
202 * @return true if cardinal was guessed, false if parsed
204 public boolean getCardinalGuessed() {
205 return _cardinalGuessed;
209 * Get the cardinal from the given character
210 * @param inChar character from file
212 protected abstract int getCardinal(char inChar);
215 * @return the default cardinal for the subclass
217 protected abstract int getDefaultCardinal();
220 * @return the maximum degree range for this coordinate
222 protected abstract int getMaxDegrees();
227 * @param inValue value of coordinate
228 * @param inFormat format to use
229 * @param inCardinal cardinal
231 protected Coordinate(double inValue, int inFormat, int inCardinal)
234 // Calculate degrees, minutes, seconds
235 _degrees = (int) Math.abs(inValue);
236 double numMins = (Math.abs(_asDouble)-_degrees) * 60.0;
237 _minutes = (int) numMins;
238 double numSecs = (numMins - _minutes) * 60.0;
239 _seconds = (int) numSecs;
240 _fracs = (int) ((numSecs - _seconds) * 10);
241 _fracDenom = 10; // fixed for now
242 // Make a string to display on screen
243 _cardinal = inCardinal;
244 _originalFormat = FORMAT_NONE;
245 if (inFormat == FORMAT_NONE) inFormat = FORMAT_DEG_WITHOUT_CARDINAL;
246 _originalString = output(inFormat);
247 _originalFormat = inFormat;
253 * @return coordinate as a double
255 public double getDouble()
261 * @return true if Coordinate is valid
263 public boolean isValid()
269 * Compares two Coordinates for equality
270 * @param inOther other Coordinate object with which to compare
271 * @return true if the two objects are equal
273 public boolean equals(Coordinate inOther)
275 return (_asDouble == inOther._asDouble);
280 * Output the Coordinate in the given format
281 * @param inFormat format to use, eg FORMAT_DEG_MIN_SEC
282 * @return String for output
284 public String output(int inFormat)
286 String answer = _originalString;
287 if (inFormat != FORMAT_NONE && inFormat != _originalFormat)
289 // TODO: allow specification of precision for output of d-m and d
290 // format as specified
293 case FORMAT_DEG_MIN_SEC:
295 StringBuffer buffer = new StringBuffer();
296 buffer.append(PRINTABLE_CARDINALS[_cardinal])
297 .append(threeDigitString(_degrees)).append('\u00B0')
298 .append(twoDigitString(_minutes)).append('\'')
299 .append(twoDigitString(_seconds)).append('.')
300 .append(formatFraction(_fracs, _fracDenom));
301 answer = buffer.toString();
306 answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
307 + FIVE_DP.format((Math.abs(_asDouble) - _degrees) * 60.0) + "'";
310 case FORMAT_DEG_WHOLE_MIN:
313 int min = (int) Math.floor(_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom + 0.5);
317 answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(deg) + "\u00B0" + min + "'";
321 case FORMAT_DEG_WITHOUT_CARDINAL:
323 if (_originalFormat != FORMAT_DEG_WITHOUT_CARDINAL)
325 answer = (_asDouble<0.0?"-":"")
326 + (_degrees + _minutes / 60.0 + _seconds / 3600.0 + _fracs / 3600.0 / _fracDenom);
330 case FORMAT_DECIMAL_FORCE_POINT:
332 // Forcing a decimal point instead of system-dependent commas etc
333 if (_originalFormat != FORMAT_DEG_WITHOUT_CARDINAL || answer.indexOf('.') < 0) {
334 answer = EIGHT_DP.format(_asDouble);
338 case FORMAT_DEG_MIN_SEC_WITH_SPACES:
340 // Note: cardinal not needed as this format is only for exif, which has cardinal separately
341 answer = "" + _degrees + " " + _minutes + " " + _seconds + "." + formatFraction(_fracs, _fracDenom);
344 case FORMAT_CARDINAL:
346 answer = "" + PRINTABLE_CARDINALS[_cardinal];
355 * Format the fraction part of seconds value
356 * @param inFrac fractional part eg 123
357 * @param inDenom denominator of fraction eg 10000
358 * @return String describing fraction, in this case 0123
360 private static final String formatFraction(int inFrac, int inDenom)
362 if (inDenom <= 1 || inFrac == 0) {return "" + inFrac;}
363 String denomString = "" + inDenom;
364 int reqdLen = denomString.length() - 1;
365 String result = denomString + inFrac;
366 int resultLen = result.length();
367 return result.substring(resultLen - reqdLen);
372 * Format an integer to a two-digit String
373 * @param inNumber number to format
374 * @return two-character String
376 private static String twoDigitString(int inNumber)
378 if (inNumber <= 0) return "00";
379 if (inNumber < 10) return "0" + inNumber;
380 if (inNumber < 100) return "" + inNumber;
381 return "" + (inNumber % 100);
386 * Format an integer to a three-digit String for degrees
387 * @param inNumber number to format
388 * @return three-character String
390 private static String threeDigitString(int inNumber)
392 if (inNumber <= 0) return "000";
393 if (inNumber < 10) return "00" + inNumber;
394 if (inNumber < 100) return "0" + inNumber;
395 return "" + (inNumber % 1000);
400 * Create a new Coordinate between two others
401 * @param inStart start coordinate
402 * @param inEnd end coordinate
403 * @param inIndex index of point
404 * @param inNumPoints number of points to interpolate
405 * @return new Coordinate object
407 public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
408 int inIndex, int inNumPoints)
410 return interpolate(inStart, inEnd, 1.0 * (inIndex+1) / (inNumPoints + 1));
415 * Create a new Coordinate between two others
416 * @param inStart start coordinate
417 * @param inEnd end coordinate
418 * @param inFraction fraction from start to end
419 * @return new Coordinate object
421 public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
424 double startValue = inStart.getDouble();
425 double endValue = inEnd.getDouble();
426 double newValue = startValue + (endValue - startValue) * inFraction;
427 Coordinate answer = inStart.makeNew(newValue, inStart._originalFormat);
433 * Make a new Coordinate according to subclass
434 * @param inValue double value
435 * @param inFormat format to use
436 * @return object of Coordinate subclass
438 protected abstract Coordinate makeNew(double inValue, int inFormat);
441 * Try to parse the given string
442 * @param inString string to check
443 * @return true if it can be parsed as a number
445 private static boolean isJustNumber(String inString)
447 boolean justNum = false;
449 double x = Double.parseDouble(inString);
450 justNum = (x >= -180.0 && x <= 360.0);
452 catch (NumberFormatException nfe) {} // flag remains false
457 * Create a String representation for debug
458 * @return String describing coordinate value
460 public String toString()
462 return "Coord: " + _cardinal + " (" + _degrees + ") (" + _minutes + ") (" + _seconds + "."
463 + formatFraction(_fracs, _fracDenom) + ") = " + _asDouble;