blob: aad69eabf224457af2650f982aa13dc37a30e882 [file] [log] [blame]
Thomas Vachuska41fe1ec2015-12-03 23:17:02 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Thomas Vachuska41fe1ec2015-12-03 23:17:02 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onlab.util;
18
19import com.google.common.base.MoreObjects;
20
21/**
22 * Geo location specified in terms of longitude and latitude.
23 */
24public class GeoLocation {
25
26 public static final double EARTH_RADIUS_KM = 6378.1370D;
27
28 private final double latitude;
29 private final double longitude;
30
31 /**
32 * Creates a new location using the specified coordinates.
33 *
34 * @param latitude latitude line
35 * @param longitude longitude line
36 */
37 public GeoLocation(double latitude, double longitude) {
38 this.latitude = latitude;
39 this.longitude = longitude;
40 }
41
42 /**
43 * Returns the latitude of this location.
44 *
45 * @return latitude
46 */
47 public double latitude() {
48 return latitude;
49 }
50
51 /**
52 * Returns the longitude of this location.
53 *
54 * @return longitude
55 */
56 public double longitude() {
57 return longitude;
58 }
59
60 /**
61 * Returns the distance in kilometers, between this location and another.
62 *
63 * @param other other geo location
64 * @return distance in kilometers
65 */
66 public double kilometersTo(GeoLocation other) {
67 double hereLat = Math.toRadians(latitude);
68 double hereLon = Math.toRadians(longitude);
69 double thereLat = Math.toRadians(other.latitude);
70 double thereLon = Math.toRadians(other.longitude);
71
72 double cos = Math.sin(hereLat) * Math.sin(thereLat) +
73 Math.cos(hereLat) * Math.cos(thereLat) * Math.cos(hereLon - thereLon);
74 return Math.acos(cos) * EARTH_RADIUS_KM;
75 }
76
77 @Override
78 public String toString() {
79 return MoreObjects.toStringHelper(this)
80 .add("latitude", latitude)
81 .add("longitude", longitude)
82 .toString();
83 }
84
85}