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");
37 private boolean _valid = false;
38 private boolean _cardinalGuessed = false;
39 protected int _cardinal = NORTH;
40 private int _degrees = 0;
41 private int _minutes = 0;
42 private int _seconds = 0;
43 private int _fracs = 0;
44 private int _fracDenom = 0;
45 private String _originalString = null;
46 private int _originalFormat = FORMAT_NONE;
47 private double _asDouble = 0.0;
51 * Constructor given String
52 * @param inString string to parse
54 public Coordinate(String inString)
56 _originalString = inString;
60 inString = inString.trim();
61 strLen = inString.length();
65 // Check for cardinal character either at beginning or end
66 boolean hasCardinal = true;
67 _cardinal = getCardinal(inString.charAt(0), inString.charAt(strLen-1));
68 if (_cardinal == NO_CARDINAL) {
70 // use default from concrete subclass
71 _cardinal = getDefaultCardinal();
72 _cardinalGuessed = true;
74 else if (isJustNumber(inString)) {
77 _cardinalGuessed = true;
80 // count numeric fields - 1=d, 2=dm, 3=dm.m/dms, 4=dms.s
82 boolean inNumeric = false;
84 long[] fields = new long[4]; // needs to be long for lengthy decimals
85 long[] denoms = new long[4];
86 boolean[] otherDelims = new boolean[5]; // remember whether delimiters have non-decimal chars
89 // Loop over characters in input string, populating fields array
90 for (int i=0; i<strLen; i++)
92 currChar = inString.charAt(i);
93 if (currChar >= '0' && currChar <= '9')
99 denoms[numFields-1] = 1;
101 if (denoms[numFields-1] < 1E18) // ignore trailing characters if too big for long
103 fields[numFields-1] = fields[numFields-1] * 10 + (currChar - '0');
104 denoms[numFields-1] *= 10;
110 // Remember delimiters
111 if (currChar != ',' && currChar != '.') {otherDelims[numFields] = true;}
114 _valid = (numFields > 0);
116 catch (ArrayIndexOutOfBoundsException obe)
118 // more than four fields found - unable to parse
121 // parse fields according to number found
122 _degrees = (int) fields[0];
123 _asDouble = _degrees;
124 _originalFormat = hasCardinal?FORMAT_DEG:FORMAT_DEG_WITHOUT_CARDINAL;
130 // String is just decimal degrees
131 double numMins = fields[1] * 60.0 / denoms[1];
132 _minutes = (int) numMins;
133 double numSecs = (numMins - _minutes) * 60.0;
134 _seconds = (int) numSecs;
135 _fracs = (int) ((numSecs - _seconds) * 10);
136 _asDouble = _degrees + 1.0 * fields[1] / denoms[1];
140 // String is degrees and minutes (due to non-decimal separator)
141 _originalFormat = FORMAT_DEG_MIN;
142 _minutes = (int) fields[1];
145 _asDouble = 1.0 * _degrees + (_minutes / 60.0);
148 // Differentiate between d-m.f and d-m-s using . or ,
149 else if (numFields == 3 && !otherDelims[2])
151 // String is degrees-minutes.fractions
152 _originalFormat = FORMAT_DEG_MIN;
153 _minutes = (int) fields[1];
154 double numSecs = fields[2] * 60.0 / denoms[2];
155 _seconds = (int) numSecs;
156 _fracs = (int) ((numSecs - _seconds) * 10);
157 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (numSecs / 3600.0);
159 else if (numFields == 4 || numFields == 3)
161 // String is degrees-minutes-seconds.fractions
162 _originalFormat = FORMAT_DEG_MIN_SEC;
163 _minutes = (int) fields[1];
164 _seconds = (int) fields[2];
165 _fracs = (int) fields[3];
166 _fracDenom = (int) denoms[3];
167 if (_fracDenom < 1) {_fracDenom = 1;}
168 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (_seconds / 3600.0) + (_fracs / 3600.0 / _fracDenom);
170 if (_cardinal == WEST || _cardinal == SOUTH || inString.charAt(0) == '-')
171 _asDouble = -_asDouble;
173 _valid = _valid && (_degrees <= getMaxDegrees() && _minutes < 60 && _seconds < 60 && _fracs < _fracDenom);
180 * Get the cardinal from the given character
181 * @param inFirstChar first character from file
182 * @param inLastChar last character from file
184 protected int getCardinal(char inFirstChar, char inLastChar)
186 // Try leading character first
187 int cardinal = getCardinal(inFirstChar);
188 // if not there, try trailing character
189 if (cardinal == NO_CARDINAL) {
190 cardinal = getCardinal(inLastChar);
196 * @return true if cardinal was guessed, false if parsed
198 public boolean getCardinalGuessed() {
199 return _cardinalGuessed;
203 * Get the cardinal from the given character
204 * @param inChar character from file
206 protected abstract int getCardinal(char inChar);
209 * @return the default cardinal for the subclass
211 protected abstract int getDefaultCardinal();
214 * @return the maximum degree range for this coordinate
216 protected abstract int getMaxDegrees();
221 * @param inValue value of coordinate
222 * @param inFormat format to use
223 * @param inCardinal cardinal
225 protected Coordinate(double inValue, int inFormat, int inCardinal)
228 // Calculate degrees, minutes, seconds
229 _degrees = (int) Math.abs(inValue);
230 double numMins = (Math.abs(_asDouble)-_degrees) * 60.0;
231 _minutes = (int) numMins;
232 double numSecs = (numMins - _minutes) * 60.0;
233 _seconds = (int) numSecs;
234 _fracs = (int) ((numSecs - _seconds) * 10);
235 _fracDenom = 10; // fixed for now
236 // Make a string to display on screen
237 _cardinal = inCardinal;
238 _originalFormat = FORMAT_NONE;
239 if (inFormat == FORMAT_NONE) inFormat = FORMAT_DEG_WITHOUT_CARDINAL;
240 _originalString = output(inFormat);
241 _originalFormat = inFormat;
247 * @return coordinate as a double
249 public double getDouble()
255 * @return true if Coordinate is valid
257 public boolean isValid()
263 * Compares two Coordinates for equality
264 * @param inOther other Coordinate object with which to compare
265 * @return true if the two objects are equal
267 public boolean equals(Coordinate inOther)
269 return (_asDouble == inOther._asDouble);
274 * Output the Coordinate in the given format
275 * @param inFormat format to use, eg FORMAT_DEG_MIN_SEC
276 * @return String for output
278 public String output(int inFormat)
280 String answer = _originalString;
281 if (inFormat != FORMAT_NONE && inFormat != _originalFormat)
283 // TODO: allow specification of precision for output of d-m and d
284 // format as specified
287 case FORMAT_DEG_MIN_SEC:
289 StringBuffer buffer = new StringBuffer();
290 buffer.append(PRINTABLE_CARDINALS[_cardinal])
291 .append(threeDigitString(_degrees)).append('\u00B0')
292 .append(twoDigitString(_minutes)).append('\'')
293 .append(twoDigitString(_seconds)).append('.')
294 .append(formatFraction(_fracs, _fracDenom));
295 answer = buffer.toString();
300 answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
301 + (_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom) + "'";
304 case FORMAT_DEG_WHOLE_MIN:
307 int min = (int) Math.floor(_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom + 0.5);
311 answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(deg) + "\u00B0" + min + "'";
315 case FORMAT_DEG_WITHOUT_CARDINAL:
317 answer = (_asDouble<0.0?"-":"")
318 + (_degrees + _minutes / 60.0 + _seconds / 3600.0 + _fracs / 3600.0 / _fracDenom);
321 case FORMAT_DECIMAL_FORCE_POINT:
323 // Forcing a decimal point instead of system-dependent commas etc
324 if (_originalFormat != FORMAT_DEG_WITHOUT_CARDINAL || answer.indexOf('.') < 0) {
325 answer = EIGHT_DP.format(_asDouble);
329 case FORMAT_DEG_MIN_SEC_WITH_SPACES:
331 // Note: cardinal not needed as this format is only for exif, which has cardinal separately
332 answer = "" + _degrees + " " + _minutes + " " + _seconds + "." + formatFraction(_fracs, _fracDenom);
335 case FORMAT_CARDINAL:
337 answer = "" + PRINTABLE_CARDINALS[_cardinal];
346 * Format the fraction part of seconds value
347 * @param inFrac fractional part eg 123
348 * @param inDenom denominator of fraction eg 10000
349 * @return String describing fraction, in this case 0123
351 private static final String formatFraction(int inFrac, int inDenom)
353 if (inDenom <= 1 || inFrac == 0) {return "" + inFrac;}
354 String denomString = "" + inDenom;
355 int reqdLen = denomString.length() - 1;
356 String result = denomString + inFrac;
357 int resultLen = result.length();
358 return result.substring(resultLen - reqdLen);
363 * Format an integer to a two-digit String
364 * @param inNumber number to format
365 * @return two-character String
367 private static String twoDigitString(int inNumber)
369 if (inNumber <= 0) return "00";
370 if (inNumber < 10) return "0" + inNumber;
371 if (inNumber < 100) return "" + inNumber;
372 return "" + (inNumber % 100);
377 * Format an integer to a three-digit String for degrees
378 * @param inNumber number to format
379 * @return three-character String
381 private static String threeDigitString(int inNumber)
383 if (inNumber <= 0) return "000";
384 if (inNumber < 10) return "00" + inNumber;
385 if (inNumber < 100) return "0" + inNumber;
386 return "" + (inNumber % 1000);
391 * Create a new Coordinate between two others
392 * @param inStart start coordinate
393 * @param inEnd end coordinate
394 * @param inIndex index of point
395 * @param inNumPoints number of points to interpolate
396 * @return new Coordinate object
398 public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
399 int inIndex, int inNumPoints)
401 return interpolate(inStart, inEnd, 1.0 * (inIndex+1) / (inNumPoints + 1));
406 * Create a new Coordinate between two others
407 * @param inStart start coordinate
408 * @param inEnd end coordinate
409 * @param inFraction fraction from start to end
410 * @return new Coordinate object
412 public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
415 double startValue = inStart.getDouble();
416 double endValue = inEnd.getDouble();
417 double newValue = startValue + (endValue - startValue) * inFraction;
418 Coordinate answer = inStart.makeNew(newValue, inStart._originalFormat);
424 * Make a new Coordinate according to subclass
425 * @param inValue double value
426 * @param inFormat format to use
427 * @return object of Coordinate subclass
429 protected abstract Coordinate makeNew(double inValue, int inFormat);
432 * Try to parse the given string
433 * @param inString string to check
434 * @return true if it can be parsed as a number
436 private static boolean isJustNumber(String inString)
438 boolean justNum = false;
440 double x = Double.parseDouble(inString);
441 justNum = (x >= -180.0 && x <= 360.0);
443 catch (NumberFormatException nfe) {} // flag remains false
448 * Create a String representation for debug
449 * @return String describing coordinate value
451 public String toString()
453 return "Coord: " + _cardinal + " (" + _degrees + ") (" + _minutes + ") (" + _seconds + "."
454 + formatFraction(_fracs, _fracDenom) + ") = " + _asDouble;