]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/data/Coordinate.java
085c502b363a5c81dfe18d45ebd583a92a3360c2
[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         /** Number formatter for fixed decimals with forced decimal point */
36         private static final NumberFormat FIVE_DP = NumberFormat.getNumberInstance(Locale.UK);
37         static {
38                 if (FIVE_DP instanceof DecimalFormat) ((DecimalFormat) FIVE_DP).applyPattern("0.00000");
39         }
40
41         // Instance variables
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;
53
54
55         /**
56          * Constructor given String
57          * @param inString string to parse
58          */
59         public Coordinate(String inString)
60         {
61                 _originalString = inString;
62                 int strLen = 0;
63                 if (inString != null)
64                 {
65                         inString = inString.trim();
66                         strLen = inString.length();
67                 }
68                 if (strLen > 0)
69                 {
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) {
74                                 hasCardinal = false;
75                                 // use default from concrete subclass
76                                 _cardinal = getDefaultCardinal();
77                                 _cardinalGuessed = true;
78                         }
79                         else if (isJustNumber(inString)) {
80                                 // it's just a number
81                                 hasCardinal = false;
82                                 _cardinalGuessed = true;
83                         }
84
85                         // count numeric fields - 1=d, 2=dm, 3=dm.m/dms, 4=dms.s
86                         int numFields = 0;
87                         boolean isNumeric = false;
88                         char currChar;
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
92                         try
93                         {
94                                 // Loop over characters in input string, populating fields array
95                                 for (int i=0; i<strLen; i++)
96                                 {
97                                         currChar = inString.charAt(i);
98                                         if (currChar >= '0' && currChar <= '9')
99                                         {
100                                                 if (!isNumeric)
101                                                 {
102                                                         isNumeric = true;
103                                                         numFields++;
104                                                         denoms[numFields-1] = 1;
105                                                 }
106                                                 if (denoms[numFields-1] < 1E18) // ignore trailing characters if too big for long
107                                                 {
108                                                         fields[numFields-1] = fields[numFields-1] * 10 + (currChar - '0');
109                                                         denoms[numFields-1] *= 10;
110                                                 }
111                                         }
112                                         else
113                                         {
114                                                 isNumeric = false;
115                                                 // Remember delimiters
116                                                 if (currChar != ',' && currChar != '.') {otherDelims[numFields] = true;}
117                                         }
118                                 }
119                                 _valid = (numFields > 0);
120                         }
121                         catch (ArrayIndexOutOfBoundsException obe)
122                         {
123                                 // more than four fields found - unable to parse
124                                 _valid = false;
125                         }
126                         // parse fields according to number found
127                         _degrees = (int) fields[0];
128                         _asDouble = _degrees;
129                         _originalFormat = hasCardinal?FORMAT_DEG:FORMAT_DEG_WITHOUT_CARDINAL;
130                         _fracDenom = 10;
131                         if (numFields == 2)
132                         {
133                                 if (!otherDelims[1])
134                                 {
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];
142                                 }
143                                 else
144                                 {
145                                         // String is degrees and minutes (due to non-decimal separator)
146                                         _originalFormat = FORMAT_DEG_MIN;
147                                         _minutes = (int) fields[1];
148                                         _seconds = 0;
149                                         _fracs = 0;
150                                         _asDouble = 1.0 * _degrees + (_minutes / 60.0);
151                                 }
152                         }
153                         // Differentiate between d-m.f and d-m-s using . or ,
154                         else if (numFields == 3 && !otherDelims[2])
155                         {
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);
163                         }
164                         else if (numFields == 4 || numFields == 3)
165                         {
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);
174                         }
175                         if (_cardinal == WEST || _cardinal == SOUTH || inString.charAt(0) == '-')
176                                 _asDouble = -_asDouble;
177                         // validate fields
178                         _valid = _valid && (_degrees <= getMaxDegrees() && _minutes < 60 && _seconds < 60 && _fracs < _fracDenom)
179                                 && Math.abs(_asDouble) <= getMaxDegrees();
180                 }
181                 else _valid = false;
182         }
183
184
185         /**
186          * Get the cardinal from the given character
187          * @param inFirstChar first character from file
188          * @param inLastChar last character from file
189          */
190         protected int getCardinal(char inFirstChar, char inLastChar)
191         {
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);
197                 }
198                 return cardinal;
199         }
200
201         /**
202          * @return true if cardinal was guessed, false if parsed
203          */
204         public boolean getCardinalGuessed() {
205                 return _cardinalGuessed;
206         }
207
208         /**
209          * Get the cardinal from the given character
210          * @param inChar character from file
211          */
212         protected abstract int getCardinal(char inChar);
213
214         /**
215          * @return the default cardinal for the subclass
216          */
217         protected abstract int getDefaultCardinal();
218
219         /**
220          * @return the maximum degree range for this coordinate
221          */
222         protected abstract int getMaxDegrees();
223
224
225         /**
226          * Constructor
227          * @param inValue value of coordinate
228          * @param inFormat format to use
229          * @param inCardinal cardinal
230          */
231         protected Coordinate(double inValue, int inFormat, int inCardinal)
232         {
233                 _asDouble = inValue;
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;
248                 _valid = true;
249         }
250
251
252         /**
253          * @return coordinate as a double
254          */
255         public double getDouble()
256         {
257                 return _asDouble;
258         }
259
260         /**
261          * @return true if Coordinate is valid
262          */
263         public boolean isValid()
264         {
265                 return _valid;
266         }
267
268         /**
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
272          */
273         public boolean equals(Coordinate inOther)
274         {
275                 return (_asDouble == inOther._asDouble);
276         }
277
278
279         /**
280          * Output the Coordinate in the given format
281          * @param inFormat format to use, eg FORMAT_DEG_MIN_SEC
282          * @return String for output
283          */
284         public String output(int inFormat)
285         {
286                 String answer = _originalString;
287                 if (inFormat != FORMAT_NONE && inFormat != _originalFormat)
288                 {
289                         // TODO: allow specification of precision for output of d-m and d
290                         // format as specified
291                         switch (inFormat)
292                         {
293                                 case FORMAT_DEG_MIN_SEC:
294                                 {
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();
302                                         break;
303                                 }
304                                 case FORMAT_DEG_MIN:
305                                 {
306                                         answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
307                                                 + FIVE_DP.format((Math.abs(_asDouble) - _degrees) * 60.0) + "'";
308                                         break;
309                                 }
310                                 case FORMAT_DEG_WHOLE_MIN:
311                                 {
312                                         int deg = _degrees;
313                                         int min = (int) Math.floor(_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom + 0.5);
314                                         if (min == 60) {
315                                                 min = 0; deg++;
316                                         }
317                                         answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(deg) + "\u00B0" + min + "'";
318                                         break;
319                                 }
320                                 case FORMAT_DEG:
321                                 case FORMAT_DEG_WITHOUT_CARDINAL:
322                                 {
323                                         if (_originalFormat != FORMAT_DEG_WITHOUT_CARDINAL)
324                                         {
325                                                 answer = (_asDouble<0.0?"-":"")
326                                                         + (_degrees + _minutes / 60.0 + _seconds / 3600.0 + _fracs / 3600.0 / _fracDenom);
327                                         }
328                                         break;
329                                 }
330                                 case FORMAT_DECIMAL_FORCE_POINT:
331                                 {
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);
335                                         }
336                                         break;
337                                 }
338                                 case FORMAT_DEG_MIN_SEC_WITH_SPACES:
339                                 {
340                                         // Note: cardinal not needed as this format is only for exif, which has cardinal separately
341                                         answer = "" + _degrees + " " + _minutes + " " + _seconds + "." + formatFraction(_fracs, _fracDenom);
342                                         break;
343                                 }
344                                 case FORMAT_CARDINAL:
345                                 {
346                                         answer = "" + PRINTABLE_CARDINALS[_cardinal];
347                                         break;
348                                 }
349                         }
350                 }
351                 return answer;
352         }
353
354         /**
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
359          */
360         private static final String formatFraction(int inFrac, int inDenom)
361         {
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);
368         }
369
370
371         /**
372          * Format an integer to a two-digit String
373          * @param inNumber number to format
374          * @return two-character String
375          */
376         private static String twoDigitString(int inNumber)
377         {
378                 if (inNumber <= 0) return "00";
379                 if (inNumber < 10) return "0" + inNumber;
380                 if (inNumber < 100) return "" + inNumber;
381                 return "" + (inNumber % 100);
382         }
383
384
385         /**
386          * Format an integer to a three-digit String for degrees
387          * @param inNumber number to format
388          * @return three-character String
389          */
390         private static String threeDigitString(int inNumber)
391         {
392                 if (inNumber <= 0) return "000";
393                 if (inNumber < 10) return "00" + inNumber;
394                 if (inNumber < 100) return "0" + inNumber;
395                 return "" + (inNumber % 1000);
396         }
397
398
399         /**
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
406          */
407         public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
408                 int inIndex, int inNumPoints)
409         {
410                 return interpolate(inStart, inEnd, 1.0 * (inIndex+1) / (inNumPoints + 1));
411         }
412
413
414         /**
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
420          */
421         public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
422                 double inFraction)
423         {
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);
428                 return answer;
429         }
430
431
432         /**
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
437          */
438         protected abstract Coordinate makeNew(double inValue, int inFormat);
439
440         /**
441          * Try to parse the given string
442          * @param inString string to check
443          * @return true if it can be parsed as a number
444          */
445         private static boolean isJustNumber(String inString)
446         {
447                 boolean justNum = false;
448                 try {
449                         double x = Double.parseDouble(inString);
450                         justNum = (x >= -180.0 && x <= 360.0);
451                 }
452                 catch (NumberFormatException nfe) {} // flag remains false
453                 return justNum;
454         }
455
456         /**
457          * Create a String representation for debug
458          * @return String describing coordinate value
459          */
460         public String toString()
461         {
462                 return "Coord: " + _cardinal + " (" + _degrees + ") (" + _minutes + ") (" + _seconds + "."
463                         + formatFraction(_fracs, _fracDenom) + ") = " + _asDouble;
464         }
465 }