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 fields[numFields-1] = fields[numFields-1] * 10 + (currChar - '0');
102 denoms[numFields-1] *= 10;
107 // Remember delimiters
108 if (currChar != ',' && currChar != '.') {otherDelims[numFields] = true;}
111 _valid = (numFields > 0);
113 catch (ArrayIndexOutOfBoundsException obe)
115 // more than four fields found - unable to parse
118 // parse fields according to number found
119 _degrees = (int) fields[0];
120 _asDouble = _degrees;
121 _originalFormat = hasCardinal?FORMAT_DEG:FORMAT_DEG_WITHOUT_CARDINAL;
127 // String is just decimal degrees
128 double numMins = fields[1] * 60.0 / denoms[1];
129 _minutes = (int) numMins;
130 double numSecs = (numMins - _minutes) * 60.0;
131 _seconds = (int) numSecs;
132 _fracs = (int) ((numSecs - _seconds) * 10);
133 _asDouble = _degrees + 1.0 * fields[1] / denoms[1];
137 // String is degrees and minutes (due to non-decimal separator)
138 _originalFormat = FORMAT_DEG_MIN;
139 _minutes = (int) fields[1];
142 _asDouble = 1.0 * _degrees + (_minutes / 60.0);
145 // Differentiate between d-m.f and d-m-s using . or ,
146 else if (numFields == 3 && !otherDelims[2])
148 // String is degrees-minutes.fractions
149 _originalFormat = FORMAT_DEG_MIN;
150 _minutes = (int) fields[1];
151 double numSecs = fields[2] * 60.0 / denoms[2];
152 _seconds = (int) numSecs;
153 _fracs = (int) ((numSecs - _seconds) * 10);
154 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (numSecs / 3600.0);
156 else if (numFields == 4 || numFields == 3)
158 // String is degrees-minutes-seconds.fractions
159 _originalFormat = FORMAT_DEG_MIN_SEC;
160 _minutes = (int) fields[1];
161 _seconds = (int) fields[2];
162 _fracs = (int) fields[3];
163 _fracDenom = (int) denoms[3];
164 if (_fracDenom < 1) {_fracDenom = 1;}
165 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (_seconds / 3600.0) + (_fracs / 3600.0 / _fracDenom);
167 if (_cardinal == WEST || _cardinal == SOUTH || inString.charAt(0) == '-')
168 _asDouble = -_asDouble;
170 _valid = _valid && (_degrees <= getMaxDegrees() && _minutes < 60 && _seconds < 60 && _fracs < _fracDenom);
177 * Get the cardinal from the given character
178 * @param inFirstChar first character from file
179 * @param inLastChar last character from file
181 protected int getCardinal(char inFirstChar, char inLastChar)
183 // Try leading character first
184 int cardinal = getCardinal(inFirstChar);
185 // if not there, try trailing character
186 if (cardinal == NO_CARDINAL) {
187 cardinal = getCardinal(inLastChar);
193 * @return true if cardinal was guessed, false if parsed
195 public boolean getCardinalGuessed() {
196 return _cardinalGuessed;
200 * Get the cardinal from the given character
201 * @param inChar character from file
203 protected abstract int getCardinal(char inChar);
206 * @return the default cardinal for the subclass
208 protected abstract int getDefaultCardinal();
211 * @return the maximum degree range for this coordinate
213 protected abstract int getMaxDegrees();
218 * @param inValue value of coordinate
219 * @param inFormat format to use
220 * @param inCardinal cardinal
222 protected Coordinate(double inValue, int inFormat, int inCardinal)
225 // Calculate degrees, minutes, seconds
226 _degrees = (int) Math.abs(inValue);
227 double numMins = (Math.abs(_asDouble)-_degrees) * 60.0;
228 _minutes = (int) numMins;
229 double numSecs = (numMins - _minutes) * 60.0;
230 _seconds = (int) numSecs;
231 _fracs = (int) ((numSecs - _seconds) * 10);
232 _fracDenom = 10; // fixed for now
233 // Make a string to display on screen
234 _cardinal = inCardinal;
235 _originalFormat = FORMAT_NONE;
236 if (inFormat == FORMAT_NONE) inFormat = FORMAT_DEG_WITHOUT_CARDINAL;
237 _originalString = output(inFormat);
238 _originalFormat = inFormat;
244 * @return coordinate as a double
246 public double getDouble()
252 * @return true if Coordinate is valid
254 public boolean isValid()
260 * Compares two Coordinates for equality
261 * @param inOther other Coordinate object with which to compare
262 * @return true if the two objects are equal
264 public boolean equals(Coordinate inOther)
266 return (_asDouble == inOther._asDouble);
271 * Output the Coordinate in the given format
272 * @param inFormat format to use, eg FORMAT_DEG_MIN_SEC
273 * @return String for output
275 public String output(int inFormat)
277 String answer = _originalString;
278 if (inFormat != FORMAT_NONE && inFormat != _originalFormat)
280 // TODO: allow specification of precision for output of d-m and d
281 // format as specified
284 case FORMAT_DEG_MIN_SEC:
286 StringBuffer buffer = new StringBuffer();
287 buffer.append(PRINTABLE_CARDINALS[_cardinal])
288 .append(threeDigitString(_degrees)).append('\u00B0')
289 .append(twoDigitString(_minutes)).append('\'')
290 .append(twoDigitString(_seconds)).append('.')
291 .append(formatFraction(_fracs, _fracDenom));
292 answer = buffer.toString();
297 answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
298 + (_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom) + "'";
301 case FORMAT_DEG_WHOLE_MIN:
304 int min = (int) Math.floor(_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom + 0.5);
308 answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(deg) + "\u00B0" + min + "'";
312 case FORMAT_DEG_WITHOUT_CARDINAL:
314 answer = (_asDouble<0.0?"-":"")
315 + (_degrees + _minutes / 60.0 + _seconds / 3600.0 + _fracs / 3600.0 / _fracDenom);
318 case FORMAT_DECIMAL_FORCE_POINT:
320 // Forcing a decimal point instead of system-dependent commas etc
321 if (_originalFormat != FORMAT_DEG_WITHOUT_CARDINAL || answer.indexOf('.') < 0) {
322 answer = EIGHT_DP.format(_asDouble);
326 case FORMAT_DEG_MIN_SEC_WITH_SPACES:
328 // Note: cardinal not needed as this format is only for exif, which has cardinal separately
329 answer = "" + _degrees + " " + _minutes + " " + _seconds + "." + formatFraction(_fracs, _fracDenom);
332 case FORMAT_CARDINAL:
334 answer = "" + PRINTABLE_CARDINALS[_cardinal];
343 * Format the fraction part of seconds value
344 * @param inFrac fractional part eg 123
345 * @param inDenom denominator of fraction eg 10000
346 * @return String describing fraction, in this case 0123
348 private static final String formatFraction(int inFrac, int inDenom)
350 if (inDenom <= 1 || inFrac == 0) {return "" + inFrac;}
351 String denomString = "" + inDenom;
352 int reqdLen = denomString.length() - 1;
353 String result = denomString + inFrac;
354 int resultLen = result.length();
355 return result.substring(resultLen - reqdLen);
360 * Format an integer to a two-digit String
361 * @param inNumber number to format
362 * @return two-character String
364 private static String twoDigitString(int inNumber)
366 if (inNumber <= 0) return "00";
367 if (inNumber < 10) return "0" + inNumber;
368 if (inNumber < 100) return "" + inNumber;
369 return "" + (inNumber % 100);
374 * Format an integer to a three-digit String for degrees
375 * @param inNumber number to format
376 * @return three-character String
378 private static String threeDigitString(int inNumber)
380 if (inNumber <= 0) return "000";
381 if (inNumber < 10) return "00" + inNumber;
382 if (inNumber < 100) return "0" + inNumber;
383 return "" + (inNumber % 1000);
388 * Create a new Coordinate between two others
389 * @param inStart start coordinate
390 * @param inEnd end coordinate
391 * @param inIndex index of point
392 * @param inNumPoints number of points to interpolate
393 * @return new Coordinate object
395 public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
396 int inIndex, int inNumPoints)
398 return interpolate(inStart, inEnd, 1.0 * (inIndex+1) / (inNumPoints + 1));
403 * Create a new Coordinate between two others
404 * @param inStart start coordinate
405 * @param inEnd end coordinate
406 * @param inFraction fraction from start to end
407 * @return new Coordinate object
409 public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
412 double startValue = inStart.getDouble();
413 double endValue = inEnd.getDouble();
414 double newValue = startValue + (endValue - startValue) * inFraction;
415 Coordinate answer = inStart.makeNew(newValue, inStart._originalFormat);
421 * Make a new Coordinate according to subclass
422 * @param inValue double value
423 * @param inFormat format to use
424 * @return object of Coordinate subclass
426 protected abstract Coordinate makeNew(double inValue, int inFormat);
429 * Try to parse the given string
430 * @param inString string to check
431 * @return true if it can be parsed as a number
433 private static boolean isJustNumber(String inString)
435 boolean justNum = false;
437 double x = Double.parseDouble(inString);
438 justNum = (x >= -180.0 && x <= 360.0);
440 catch (NumberFormatException nfe) {} // flag remains false
445 * Create a String representation for debug
446 * @return String describing coordinate value
448 public String toString()
450 return "Coord: " + _cardinal + " (" + _degrees + ") (" + _minutes + ") (" + _seconds + "."
451 + formatFraction(_fracs, _fracDenom) + ") = " + _asDouble;