878da03e2b6a7ad2ade1e87fc97a19fa80055315
[fw/altos] / ao-tools / altosui / AltosGreatCircle.java
1 /*
2  * Copyright © 2010 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package altosui;
19
20 import java.lang.Math;
21
22 public class AltosGreatCircle {
23         double  distance;
24         double  bearing;
25
26         double sqr(double a) { return a * a; }
27
28         static final double rad = Math.PI / 180;
29         static final double earth_radius = 6371.2 * 1000;       /* in meters */
30
31         AltosGreatCircle (double start_lat, double start_lon,
32                           double end_lat, double end_lon)
33         {
34                 double lat1 = rad * start_lat;
35                 double lon1 = rad * -start_lon;
36                 double lat2 = rad * end_lat;
37                 double lon2 = rad * -end_lon;
38
39                 double d_lon = lon2 - lon1;
40
41                 /* From http://en.wikipedia.org/wiki/Great-circle_distance */
42                 double vdn = Math.sqrt(sqr(Math.cos(lat2) * Math.sin(d_lon)) +
43                                        sqr(Math.cos(lat1) * Math.sin(lat2) -
44                                            Math.sin(lat1) * Math.cos(lat2) * Math.cos(d_lon)));
45                 double vdd = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(d_lon);
46                 double d = Math.atan2(vdn,vdd);
47                 double course;
48
49                 if (Math.cos(lat1) < 1e-20) {
50                         if (lat1 > 0)
51                                 course = Math.PI;
52                         else
53                                 course = -Math.PI;
54                 } else {
55                         if (d < 1e-10)
56                                 course = 0;
57                         else
58                                 course = Math.acos((Math.sin(lat2)-Math.sin(lat1)*Math.cos(d)) /
59                                                    (Math.sin(d)*Math.cos(lat1)));
60                         if (Math.sin(lon2-lon1) > 0)
61                                 course = 2 * Math.PI-course;
62                 }
63                 distance = d * earth_radius;
64                 bearing = course * 180/Math.PI;
65         }
66 }