]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/data/Coordinate.java
190c66573b13e2c251a434407bc02315d34c0984
[GpsPrune.git] / tim / prune / data / Coordinate.java
1 package tim.prune.data;
2
3 import java.text.DecimalFormat;
4 import java.text.NumberFormat;
5 import java.util.Locale;
6
7 /**
8  * Class to represent a lat/long coordinate
9  * and provide conversion functions
10  */
11 public abstract class Coordinate
12 {
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;
28
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)
32         static {
33                 if (EIGHT_DP instanceof DecimalFormat) ((DecimalFormat) EIGHT_DP).applyPattern("0.00000000");
34         }
35
36         // Instance variables
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;
48
49
50         /**
51          * Constructor given String
52          * @param inString string to parse
53          */
54         public Coordinate(String inString)
55         {
56                 _originalString = inString;
57                 int strLen = 0;
58                 if (inString != null)
59                 {
60                         inString = inString.trim();
61                         strLen = inString.length();
62                 }
63                 if (strLen > 1)
64                 {
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) {
69                                 hasCardinal = false;
70                                 // use default from concrete subclass
71                                 _cardinal = getDefaultCardinal();
72                                 _cardinalGuessed = true;
73                         }
74                         else if (isJustNumber(inString)) {
75                                 // it's just a number
76                                 hasCardinal = false;
77                                 _cardinalGuessed = true;
78                         }
79
80                         // count numeric fields - 1=d, 2=dm, 3=dm.m/dms, 4=dms.s
81                         int numFields = 0;
82                         boolean inNumeric = false;
83                         char currChar;
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
87                         try
88                         {
89                                 // Loop over characters in input string, populating fields array
90                                 for (int i=0; i<strLen; i++)
91                                 {
92                                         currChar = inString.charAt(i);
93                                         if (currChar >= '0' && currChar <= '9')
94                                         {
95                                                 if (!inNumeric)
96                                                 {
97                                                         inNumeric = true;
98                                                         numFields++;
99                                                         denoms[numFields-1] = 1;
100                                                 }
101                                                 fields[numFields-1] = fields[numFields-1] * 10 + (currChar - '0');
102                                                 denoms[numFields-1] *= 10;
103                                         }
104                                         else
105                                         {
106                                                 inNumeric = false;
107                                                 // Remember delimiters
108                                                 if (currChar != ',' && currChar != '.') {otherDelims[numFields] = true;}
109                                         }
110                                 }
111                                 _valid = (numFields > 0);
112                         }
113                         catch (ArrayIndexOutOfBoundsException obe)
114                         {
115                                 // more than four fields found - unable to parse
116                                 _valid = false;
117                         }
118                         // parse fields according to number found
119                         _degrees = (int) fields[0];
120                         _originalFormat = hasCardinal?FORMAT_DEG:FORMAT_DEG_WITHOUT_CARDINAL;
121                         _fracDenom = 10;
122                         if (numFields == 2)
123                         {
124                                 if (!otherDelims[1])
125                                 {
126                                         // String is just decimal degrees
127                                         double numMins = fields[1] * 60.0 / denoms[1];
128                                         _minutes = (int) numMins;
129                                         double numSecs = (numMins - _minutes) * 60.0;
130                                         _seconds = (int) numSecs;
131                                         _fracs = (int) ((numSecs - _seconds) * 10);
132                                         _asDouble = _degrees + 1.0 * fields[1] / denoms[1];
133                                 }
134                                 else
135                                 {
136                                         // String is degrees and minutes (due to non-decimal separator)
137                                         _originalFormat = FORMAT_DEG_MIN;
138                                         _minutes = (int) fields[1];
139                                         _seconds = 0;
140                                         _fracs = 0;
141                                         _asDouble = 1.0 * _degrees + (_minutes / 60.0);
142                                 }
143                         }
144                         // Differentiate between d-m.f and d-m-s using . or ,
145                         else if (numFields == 3 && !otherDelims[2])
146                         {
147                                 // String is degrees-minutes.fractions
148                                 _originalFormat = FORMAT_DEG_MIN;
149                                 _minutes = (int) fields[1];
150                                 double numSecs = fields[2] * 60.0 / denoms[2];
151                                 _seconds = (int) numSecs;
152                                 _fracs = (int) ((numSecs - _seconds) * 10);
153                                 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (numSecs / 3600.0);
154                         }
155                         else if (numFields == 4 || numFields == 3)
156                         {
157                                 // String is degrees-minutes-seconds.fractions
158                                 _originalFormat = FORMAT_DEG_MIN_SEC;
159                                 _minutes = (int) fields[1];
160                                 _seconds = (int) fields[2];
161                                 _fracs = (int) fields[3];
162                                 _fracDenom = (int) denoms[3];
163                                 if (_fracDenom < 1) {_fracDenom = 1;}
164                                 _asDouble = 1.0 * _degrees + (_minutes / 60.0) + (_seconds / 3600.0) + (_fracs / 3600.0 / _fracDenom);
165                         }
166                         if (_cardinal == WEST || _cardinal == SOUTH || inString.charAt(0) == '-')
167                                 _asDouble = -_asDouble;
168                         // validate fields
169                         _valid = _valid && (_degrees <= getMaxDegrees() && _minutes < 60 && _seconds < 60 && _fracs < _fracDenom);
170                 }
171                 else _valid = false;
172         }
173
174
175         /**
176          * Get the cardinal from the given character
177          * @param inFirstChar first character from file
178          * @param inLastChar last character from file
179          */
180         protected int getCardinal(char inFirstChar, char inLastChar)
181         {
182                 // Try leading character first
183                 int cardinal = getCardinal(inFirstChar);
184                 // if not there, try trailing character
185                 if (cardinal == NO_CARDINAL) {
186                         cardinal = getCardinal(inLastChar);
187                 }
188                 return cardinal;
189         }
190
191         /**
192          * @return true if cardinal was guessed, false if parsed
193          */
194         public boolean getCardinalGuessed() {
195                 return _cardinalGuessed;
196         }
197
198         /**
199          * Get the cardinal from the given character
200          * @param inChar character from file
201          */
202         protected abstract int getCardinal(char inChar);
203
204         /**
205          * @return the default cardinal for the subclass
206          */
207         protected abstract int getDefaultCardinal();
208
209         /**
210          * @return the maximum degree range for this coordinate
211          */
212         protected abstract int getMaxDegrees();
213
214
215         /**
216          * Constructor
217          * @param inValue value of coordinate
218          * @param inFormat format to use
219          * @param inCardinal cardinal
220          */
221         protected Coordinate(double inValue, int inFormat, int inCardinal)
222         {
223                 _asDouble = inValue;
224                 // Calculate degrees, minutes, seconds
225                 _degrees = (int) Math.abs(inValue);
226                 double numMins = (Math.abs(_asDouble)-_degrees) * 60.0;
227                 _minutes = (int) numMins;
228                 double numSecs = (numMins - _minutes) * 60.0;
229                 _seconds = (int) numSecs;
230                 _fracs = (int) ((numSecs - _seconds) * 10);
231                 _fracDenom = 10; // fixed for now
232                 // Make a string to display on screen
233                 _cardinal = inCardinal;
234                 _originalFormat = FORMAT_NONE;
235                 if (inFormat == FORMAT_NONE) inFormat = FORMAT_DEG_WITHOUT_CARDINAL;
236                 _originalString = output(inFormat);
237                 _originalFormat = inFormat;
238                 _valid = true;
239         }
240
241
242         /**
243          * @return coordinate as a double
244          */
245         public double getDouble()
246         {
247                 return _asDouble;
248         }
249
250         /**
251          * @return true if Coordinate is valid
252          */
253         public boolean isValid()
254         {
255                 return _valid;
256         }
257
258         /**
259          * Compares two Coordinates for equality
260          * @param inOther other Coordinate object with which to compare
261          * @return true if the two objects are equal
262          */
263         public boolean equals(Coordinate inOther)
264         {
265                 return (inOther != null && _cardinal == inOther._cardinal
266                         && _degrees == inOther._degrees
267                         && _minutes == inOther._minutes
268                         && _seconds == inOther._seconds
269                         && _fracs == inOther._fracs);
270         }
271
272
273         /**
274          * Output the Coordinate in the given format
275          * @param inFormat format to use, eg FORMAT_DEG_MIN_SEC
276          * @return String for output
277          */
278         public String output(int inFormat)
279         {
280                 String answer = _originalString;
281                 if (inFormat != FORMAT_NONE && inFormat != _originalFormat)
282                 {
283                         // TODO: allow specification of precision for output of d-m and d
284                         // format as specified
285                         switch (inFormat)
286                         {
287                                 case FORMAT_DEG_MIN_SEC:
288                                 {
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();
296                                         break;
297                                 }
298                                 case FORMAT_DEG_MIN:
299                                 {
300                                         answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
301                                                 + (_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom) + "'";
302                                         break;
303                                 }
304                                 case FORMAT_DEG_WHOLE_MIN:
305                                 {
306                                         answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
307                                                 + (int) Math.floor(_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom + 0.5) + "'";
308                                         break;
309                                 }
310                                 case FORMAT_DEG:
311                                 case FORMAT_DEG_WITHOUT_CARDINAL:
312                                 {
313                                         answer = (_asDouble<0.0?"-":"")
314                                                 + (_degrees + _minutes / 60.0 + _seconds / 3600.0 + _fracs / 3600.0 / _fracDenom);
315                                         break;
316                                 }
317                                 case FORMAT_DECIMAL_FORCE_POINT:
318                                 {
319                                         // Forcing a decimal point instead of system-dependent commas etc
320                                         if (_originalFormat != FORMAT_DEG_WITHOUT_CARDINAL || answer.indexOf('.') < 0) {
321                                                 answer = EIGHT_DP.format(_asDouble);
322                                         }
323                                         break;
324                                 }
325                                 case FORMAT_DEG_MIN_SEC_WITH_SPACES:
326                                 {
327                                         // Note: cardinal not needed as this format is only for exif, which has cardinal separately
328                                         answer = "" + _degrees + " " + _minutes + " " + _seconds + "." + formatFraction(_fracs, _fracDenom);
329                                         break;
330                                 }
331                                 case FORMAT_CARDINAL:
332                                 {
333                                         answer = "" + PRINTABLE_CARDINALS[_cardinal];
334                                         break;
335                                 }
336                         }
337                 }
338                 return answer;
339         }
340
341         /**
342          * Format the fraction part of seconds value
343          * @param inFrac fractional part eg 123
344          * @param inDenom denominator of fraction eg 10000
345          * @return String describing fraction, in this case 0123
346          */
347         private static final String formatFraction(int inFrac, int inDenom)
348         {
349                 if (inDenom <= 1 || inFrac == 0) {return "" + inFrac;}
350                 String denomString = "" + inDenom;
351                 int reqdLen = denomString.length() - 1;
352                 String result = denomString + inFrac;
353                 int resultLen = result.length();
354                 return result.substring(resultLen - reqdLen);
355         }
356
357
358         /**
359          * Format an integer to a two-digit String
360          * @param inNumber number to format
361          * @return two-character String
362          */
363         private static String twoDigitString(int inNumber)
364         {
365                 if (inNumber <= 0) return "00";
366                 if (inNumber < 10) return "0" + inNumber;
367                 if (inNumber < 100) return "" + inNumber;
368                 return "" + (inNumber % 100);
369         }
370
371
372         /**
373          * Format an integer to a three-digit String for degrees
374          * @param inNumber number to format
375          * @return three-character String
376          */
377         private static String threeDigitString(int inNumber)
378         {
379                 if (inNumber <= 0) return "000";
380                 if (inNumber < 10) return "00" + inNumber;
381                 if (inNumber < 100) return "0" + inNumber;
382                 return "" + (inNumber % 1000);
383         }
384
385
386         /**
387          * Create a new Coordinate between two others
388          * @param inStart start coordinate
389          * @param inEnd end coordinate
390          * @param inIndex index of point
391          * @param inNumPoints number of points to interpolate
392          * @return new Coordinate object
393          */
394         public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
395                 int inIndex, int inNumPoints)
396         {
397                 return interpolate(inStart, inEnd, 1.0 * (inIndex+1) / (inNumPoints + 1));
398         }
399
400
401         /**
402          * Create a new Coordinate between two others
403          * @param inStart start coordinate
404          * @param inEnd end coordinate
405          * @param inFraction fraction from start to end
406          * @return new Coordinate object
407          */
408         public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
409                 double inFraction)
410         {
411                 double startValue = inStart.getDouble();
412                 double endValue = inEnd.getDouble();
413                 double newValue = startValue + (endValue - startValue) * inFraction;
414                 Coordinate answer = inStart.makeNew(newValue, inStart._originalFormat);
415                 return answer;
416         }
417
418
419         /**
420          * Make a new Coordinate according to subclass
421          * @param inValue double value
422          * @param inFormat format to use
423          * @return object of Coordinate subclass
424          */
425         protected abstract Coordinate makeNew(double inValue, int inFormat);
426
427         /**
428          * Try to parse the given string
429          * @param inString string to check
430          * @return true if it can be parsed as a number
431          */
432         private static boolean isJustNumber(String inString)
433         {
434                 boolean justNum = false;
435                 try {
436                         double x = Double.parseDouble(inString);
437                         justNum = (x >= -180.0 && x <= 360.0);
438                 }
439                 catch (NumberFormatException nfe) {} // flag remains false
440                 return justNum;
441         }
442
443         /**
444          * Create a String representation for debug
445          * @return String describing coordinate value
446          */
447         public String toString()
448         {
449                 return "Coord: " + _cardinal + " (" + _degrees + ") (" + _minutes + ") (" + _seconds + "."
450                         + formatFraction(_fracs, _fracDenom) + ") = " + _asDouble;
451         }
452 }