]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/data/Coordinate.java
44ab779ab6c1a0d66f1254c3df6fb82391a955fb
[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                         _asDouble = _degrees;
121                         _originalFormat = hasCardinal?FORMAT_DEG:FORMAT_DEG_WITHOUT_CARDINAL;
122                         _fracDenom = 10;
123                         if (numFields == 2)
124                         {
125                                 if (!otherDelims[1])
126                                 {
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];
134                                 }
135                                 else
136                                 {
137                                         // String is degrees and minutes (due to non-decimal separator)
138                                         _originalFormat = FORMAT_DEG_MIN;
139                                         _minutes = (int) fields[1];
140                                         _seconds = 0;
141                                         _fracs = 0;
142                                         _asDouble = 1.0 * _degrees + (_minutes / 60.0);
143                                 }
144                         }
145                         // Differentiate between d-m.f and d-m-s using . or ,
146                         else if (numFields == 3 && !otherDelims[2])
147                         {
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);
155                         }
156                         else if (numFields == 4 || numFields == 3)
157                         {
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);
166                         }
167                         if (_cardinal == WEST || _cardinal == SOUTH || inString.charAt(0) == '-')
168                                 _asDouble = -_asDouble;
169                         // validate fields
170                         _valid = _valid && (_degrees <= getMaxDegrees() && _minutes < 60 && _seconds < 60 && _fracs < _fracDenom);
171                 }
172                 else _valid = false;
173         }
174
175
176         /**
177          * Get the cardinal from the given character
178          * @param inFirstChar first character from file
179          * @param inLastChar last character from file
180          */
181         protected int getCardinal(char inFirstChar, char inLastChar)
182         {
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);
188                 }
189                 return cardinal;
190         }
191
192         /**
193          * @return true if cardinal was guessed, false if parsed
194          */
195         public boolean getCardinalGuessed() {
196                 return _cardinalGuessed;
197         }
198
199         /**
200          * Get the cardinal from the given character
201          * @param inChar character from file
202          */
203         protected abstract int getCardinal(char inChar);
204
205         /**
206          * @return the default cardinal for the subclass
207          */
208         protected abstract int getDefaultCardinal();
209
210         /**
211          * @return the maximum degree range for this coordinate
212          */
213         protected abstract int getMaxDegrees();
214
215
216         /**
217          * Constructor
218          * @param inValue value of coordinate
219          * @param inFormat format to use
220          * @param inCardinal cardinal
221          */
222         protected Coordinate(double inValue, int inFormat, int inCardinal)
223         {
224                 _asDouble = inValue;
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;
239                 _valid = true;
240         }
241
242
243         /**
244          * @return coordinate as a double
245          */
246         public double getDouble()
247         {
248                 return _asDouble;
249         }
250
251         /**
252          * @return true if Coordinate is valid
253          */
254         public boolean isValid()
255         {
256                 return _valid;
257         }
258
259         /**
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
263          */
264         public boolean equals(Coordinate inOther)
265         {
266                 return (inOther != null && _cardinal == inOther._cardinal
267                         && _degrees == inOther._degrees
268                         && _minutes == inOther._minutes
269                         && _seconds == inOther._seconds
270                         && _fracs == inOther._fracs);
271         }
272
273
274         /**
275          * Output the Coordinate in the given format
276          * @param inFormat format to use, eg FORMAT_DEG_MIN_SEC
277          * @return String for output
278          */
279         public String output(int inFormat)
280         {
281                 String answer = _originalString;
282                 if (inFormat != FORMAT_NONE && inFormat != _originalFormat)
283                 {
284                         // TODO: allow specification of precision for output of d-m and d
285                         // format as specified
286                         switch (inFormat)
287                         {
288                                 case FORMAT_DEG_MIN_SEC:
289                                 {
290                                         StringBuffer buffer = new StringBuffer();
291                                         buffer.append(PRINTABLE_CARDINALS[_cardinal])
292                                                 .append(threeDigitString(_degrees)).append('\u00B0')
293                                                 .append(twoDigitString(_minutes)).append('\'')
294                                                 .append(twoDigitString(_seconds)).append('.')
295                                                 .append(formatFraction(_fracs, _fracDenom));
296                                         answer = buffer.toString();
297                                         break;
298                                 }
299                                 case FORMAT_DEG_MIN:
300                                 {
301                                         answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
302                                                 + (_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom) + "'";
303                                         break;
304                                 }
305                                 case FORMAT_DEG_WHOLE_MIN:
306                                 {
307                                         answer = "" + PRINTABLE_CARDINALS[_cardinal] + threeDigitString(_degrees) + "\u00B0"
308                                                 + (int) Math.floor(_minutes + _seconds / 60.0 + _fracs / 60.0 / _fracDenom + 0.5) + "'";
309                                         break;
310                                 }
311                                 case FORMAT_DEG:
312                                 case FORMAT_DEG_WITHOUT_CARDINAL:
313                                 {
314                                         answer = (_asDouble<0.0?"-":"")
315                                                 + (_degrees + _minutes / 60.0 + _seconds / 3600.0 + _fracs / 3600.0 / _fracDenom);
316                                         break;
317                                 }
318                                 case FORMAT_DECIMAL_FORCE_POINT:
319                                 {
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);
323                                         }
324                                         break;
325                                 }
326                                 case FORMAT_DEG_MIN_SEC_WITH_SPACES:
327                                 {
328                                         // Note: cardinal not needed as this format is only for exif, which has cardinal separately
329                                         answer = "" + _degrees + " " + _minutes + " " + _seconds + "." + formatFraction(_fracs, _fracDenom);
330                                         break;
331                                 }
332                                 case FORMAT_CARDINAL:
333                                 {
334                                         answer = "" + PRINTABLE_CARDINALS[_cardinal];
335                                         break;
336                                 }
337                         }
338                 }
339                 return answer;
340         }
341
342         /**
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
347          */
348         private static final String formatFraction(int inFrac, int inDenom)
349         {
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);
356         }
357
358
359         /**
360          * Format an integer to a two-digit String
361          * @param inNumber number to format
362          * @return two-character String
363          */
364         private static String twoDigitString(int inNumber)
365         {
366                 if (inNumber <= 0) return "00";
367                 if (inNumber < 10) return "0" + inNumber;
368                 if (inNumber < 100) return "" + inNumber;
369                 return "" + (inNumber % 100);
370         }
371
372
373         /**
374          * Format an integer to a three-digit String for degrees
375          * @param inNumber number to format
376          * @return three-character String
377          */
378         private static String threeDigitString(int inNumber)
379         {
380                 if (inNumber <= 0) return "000";
381                 if (inNumber < 10) return "00" + inNumber;
382                 if (inNumber < 100) return "0" + inNumber;
383                 return "" + (inNumber % 1000);
384         }
385
386
387         /**
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
394          */
395         public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
396                 int inIndex, int inNumPoints)
397         {
398                 return interpolate(inStart, inEnd, 1.0 * (inIndex+1) / (inNumPoints + 1));
399         }
400
401
402         /**
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
408          */
409         public static Coordinate interpolate(Coordinate inStart, Coordinate inEnd,
410                 double inFraction)
411         {
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);
416                 return answer;
417         }
418
419
420         /**
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
425          */
426         protected abstract Coordinate makeNew(double inValue, int inFormat);
427
428         /**
429          * Try to parse the given string
430          * @param inString string to check
431          * @return true if it can be parsed as a number
432          */
433         private static boolean isJustNumber(String inString)
434         {
435                 boolean justNum = false;
436                 try {
437                         double x = Double.parseDouble(inString);
438                         justNum = (x >= -180.0 && x <= 360.0);
439                 }
440                 catch (NumberFormatException nfe) {} // flag remains false
441                 return justNum;
442         }
443
444         /**
445          * Create a String representation for debug
446          * @return String describing coordinate value
447          */
448         public String toString()
449         {
450                 return "Coord: " + _cardinal + " (" + _degrees + ") (" + _minutes + ") (" + _seconds + "."
451                         + formatFraction(_fracs, _fracDenom) + ") = " + _asDouble;
452         }
453 }