aboutsummaryrefslogtreecommitdiffstats
path: root/src/cgeo/geocaching/geopoint/Geopoint.java
blob: a8d7d37c8437bc48aef1ca0bfae07ec5c82c8bff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package cgeo.geocaching.geopoint;

import android.location.Location;

/**
 * Abstraction of geographic point.
 */
public class Geopoint
{
    public static final double kmInMiles = 1 / 1.609344;
    public static final double deg2rad   = Math.PI / 180;
    public static final double rad2deg   = 180 / Math.PI;
    public static final float  erad      = 6371.0f;

    private double latitude;
    private double longitude;

    /**
     * Creates new Geopoint with given latitude and longitude (both degree).
     *
     * @param lat latitude
     * @param lon longitude
     */
    public Geopoint(final double lat, final double lon)
    {
        setLatitude(lat);
        setLongitude(lon);
    }
    
    /**
     * Creates new Geopoint with given latitude and longitude (both microdegree).
     *
     * @param lat latitude
     * @param lon longitude
     */
    public Geopoint(final int lat, final int lon)
    {
        setLatitude(lat * 1E-6);
        setLongitude(lon * 1E-6);
    }

    /**
     * Creates new Geopoint with latitude and longitude parsed from string.
     *
     * @param text string to parse
     * @see GeopointParser.parse()
     */
    public Geopoint(final String text)
    {
        setLatitude(GeopointParser.parseLatitude(text));
        setLongitude(GeopointParser.parseLongitude(text));
    }

    /**
     * Creates new Geopoint with given Geopoint. This is similar to clone().
     *
     * @param gp the Geopoint to clone
     */
    public Geopoint(final Geopoint gp)
    {
        this(gp.getLatitude(), gp.getLongitude());
    }

    /**
     * Creates new Geopoint with given Location.
     *
     * @param gp the Location to clone
     */
    public Geopoint(final Location loc) {
        this(loc.getLatitude(), loc.getLongitude());
    }

	/**
     * Set latitude in degree.
     *
     * @param lat latitude
     * @return this
     * @throws MalformedCoordinateException if not -90 <= lat <= 90
     */
    private void setLatitude(final double lat)
    {
        if (lat <= 90 && lat >= -90)
        {
            latitude  = lat;
        }
        else
        {
            throw new MalformedCoordinateException("malformed latitude: " + lat);
        }
    }

    /**
     * Get latitude in degree.
     *
     * @return latitude
     */
    public double getLatitude()
    {
        return latitude;
    }

    /**
     * Get latitude in microdegree.
     *
     * @return latitude
     */
    public int getLatitudeE6()
    {
        return (int) (latitude * 1E6);
    }

    /**
     * Set longitude in degree.
     *
     * @param lon longitude
     * @return this
     * @throws MalformedCoordinateException if not -180 <= lon <= 180
     */
    private void setLongitude(final double lon)
    {
        if (lon <= 180 && lon >=-180)
        {
            longitude = lon;
        }
        else
        {
            throw new MalformedCoordinateException("malformed longitude: " + lon);
        }
    }

    /**
     * Get longitude in degree.
     *
     * @return longitude
     */
    public double getLongitude()
    {
        return longitude;
    }

    /**
     * Get longitude in microdegree.
     *
     * @return longitude
     */
    public int getLongitudeE6()
    {
        return (int) (longitude * 1E6);
    }

    /**
     * Calculates distance to given Geopoint in km.
     *
     * @param gp target
     * @return distance in km
     * @throws GeopointException if there is an error in distance calculation
     */
    public double distanceTo(final Geopoint gp)
    {
        final double lat1 = deg2rad * latitude;
        final double lon1 = deg2rad * longitude;
        final double lat2 = deg2rad * gp.getLatitude();
        final double lon2 = deg2rad * gp.getLongitude();

        final double d = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2);
        final double distance = erad * Math.acos(d); // distance in km

        if (!Double.isNaN(distance) && distance > 0)
        {
            return distance;
        }
        else
        {
            throw new GeopointException("Error in distance calculation.");
        }
    }

    /**
     * Calculates bearing to given Geopoint in degree.
     *
     * @param gp target
     * @return bearing in degree.
     */
    public double bearingTo(final Geopoint gp)
    {
        final int ilat1 = (int) Math.round(0.5 + latitude * 360000);
        final int ilon1 = (int) Math.round(0.5 + longitude * 360000);
        final int ilat2 = (int) Math.round(0.5 + gp.getLatitude() * 360000);
        final int ilon2 = (int) Math.round(0.5 + gp.getLongitude() * 360000);

        final double lat1 = deg2rad * latitude;
        final double lon1 = deg2rad * longitude;
        final double lat2 = deg2rad * gp.getLatitude();
        final double lon2 = deg2rad * gp.getLongitude();

        if (ilat1 == ilat2 && ilon1 == ilon2)
        {
            return 0;
        }
        else if (ilat1 == ilat2)
        {
            return (ilon1 > ilon2) ? 270 : 90;
        }
        else if (ilon1 == ilon2)
        {
            return (ilat1 > ilat2) ? 180: 0;
        }
        else
        {
            double c = Math.acos(Math.sin(lat2) * Math.sin(lat1) + Math.cos(lat2) * Math.cos(lat1) * Math.cos(lon2 - lon1));
            double A = Math.asin(Math.cos(lat2) * Math.sin(lon2 - lon1) / Math.sin(c));
            double result = A * rad2deg;

            if (ilat2 > ilat1 && ilon2 > ilon1)
            {
                // result don't need change
            }
            else if (ilat2 < ilat1 && ilon2 < ilon1)
            {
                result = 180f - result;
            }
            else if (ilat2 < ilat1 && ilon2 > ilon1)
            {
                result = 180f - result;
            }
            else if (ilat2 > ilat1 && ilon2 < ilon1)
            {
                result += 360f;
            }

            return result;
        }
    }

    /**
     * Calculates geopoint from given bearing and distance.
     *
     * @param bearing bearing in degree
     * @param distance distance in km
     * @return the projected geopoint
     */
    public Geopoint project(final double bearing, final double distance)
    {
        final double rlat1     = latitude * deg2rad;
        final double rlon1     = longitude * deg2rad;
        final double rbearing  = bearing * deg2rad;
        final double rdistance = distance / erad;

        final double rlat = Math.asin(Math.sin(rlat1) * Math.cos(rdistance) + Math.cos(rlat1) * Math.sin(rdistance) * Math.cos(rbearing));
        final double rlon = rlon1 + Math.atan2(Math.sin(rbearing) * Math.sin(rdistance) * Math.cos(rlat1), Math.cos(rdistance) - Math.sin(rlat1) * Math.sin(rlat));

        return new Geopoint(rlat * rad2deg, rlon * rad2deg);
    }

    /**
     * Checks if given Geopoint is identical with this Geopoint.
     *
     * @param gp Geopoint to check
     * @return true if identical, false otherwise
     */
    public boolean isEqualTo(Geopoint gp)
    {
        return null != gp && gp.getLatitude() == latitude && gp.getLongitude() == longitude;
    }

    /**
     * Checks if given Geopoint is similar to this Geopoint with tolerance.
     *
     * @param gp Geopoint to check
     * @param tolerance tolerance in km
     * @return true if similar, false otherwise
     */
    public boolean isEqualTo(Geopoint gp, double tolerance)
    {
        return null != gp && distanceTo(gp) <= tolerance;
    }

    /**
     * Returns formatted coordinates.
     *
     * @param format the desired format
     * @see GeopointFormatter
     * @return formatted coordinates
     */
    public String format(GeopointFormatter format)
    {
        return format.format(this);
    }

    /**
     * Returns formatted coordinates.
     *
     * @param format the desired format
     * @see GeopointFormatter
     * @return formatted coordinates
     */
    public String format(String format)
    {
        return GeopointFormatter.format(format, this);
    }

    /**
     * Returns formatted coordinates.
     *
     * @param format the desired format
     * @see GeopointFormatter
     * @return formatted coordinates
     */
    public String format(GeopointFormatter.Format format)
    {
        return GeopointFormatter.format(format, this);
    }

    /**
     * Returns formatted coordinates with default format.
     * Default format is decimalminutes, e.g. N 52° 36.123 E 010° 03.456
     *
     * @return formatted coordinates
     */
    public String toString()
    {
        return format(GeopointFormatter.Format.LAT_LON_DECMINUTE);
    }

    public static class GeopointException
        extends RuntimeException
    {
        private static final long serialVersionUID = 1L;

        public GeopointException(String msg)
        {
            super(msg);
        }
    }

    public static class MalformedCoordinateException
        extends GeopointException
    {
        private static final long serialVersionUID = 1L;

        public MalformedCoordinateException(String msg)
        {
            super(msg);
        }
    }
}