001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.coor;
003
004import static java.lang.Math.PI;
005import static java.lang.Math.asin;
006import static java.lang.Math.atan2;
007import static java.lang.Math.cos;
008import static java.lang.Math.sin;
009import static java.lang.Math.sqrt;
010import static org.openstreetmap.josm.data.projection.Ellipsoid.WGS84;
011import static org.openstreetmap.josm.tools.Utils.toRadians;
012
013import org.openstreetmap.josm.data.projection.Projecting;
014import org.openstreetmap.josm.tools.Logging;
015
016/**
017 * This interface represents a coordinate in LatLon space.
018 * <p>
019 * It provides methods to get the coordinates. The coordinates may be unknown.
020 * In this case, both {@link #lat()} and {@link #lon()} need to return a NaN value and {@link #isLatLonKnown()} needs to return false.
021 * <p>
022 * Whether the coordinates are immutable or not is implementation specific.
023 *
024 * @author Michael Zangl
025 * @since 12161
026 */
027public interface ILatLon {
028    /**
029     * Minimum difference in location to not be represented as the same position.
030     * The API returns 7 decimals.
031     */
032    double MAX_SERVER_PRECISION = 1e-7;
033
034    /**
035     * Returns the longitude, i.e., the east-west position in degrees.
036     * @return the longitude or NaN if {@link #isLatLonKnown()} returns false
037     */
038    double lon();
039
040    /**
041     * Returns the latitude, i.e., the north-south position in degrees.
042     * @return the latitude or NaN if {@link #isLatLonKnown()} returns false
043     */
044    double lat();
045
046    /**
047     * Determines if this object has valid coordinates.
048     * @return {@code true} if this object has valid coordinates
049     */
050    default boolean isLatLonKnown() {
051        return !Double.isNaN(lat()) && !Double.isNaN(lon());
052    }
053
054    /**
055     * Replies the projected east/north coordinates.
056     * <p>
057     * The result of the last conversion may be cached. Null is returned in case this object is invalid.
058     * @param projecting The projection to use.
059     * @return The projected east/north coordinates
060     * @since 10827
061     */
062    default EastNorth getEastNorth(Projecting projecting) {
063        if (!isLatLonKnown()) {
064            return null;
065        } else {
066            return projecting.latlon2eastNorth(this);
067        }
068    }
069
070    /**
071     * Determines if the other point has almost the same lat/lon values.
072     * @param other other lat/lon
073     * @return <code>true</code> if the other point has almost the same lat/lon
074     * values, only differing by no more than 1 / {@link #MAX_SERVER_PRECISION MAX_SERVER_PRECISION}.
075     * @since 18464
076     */
077    default boolean equalsEpsilon(ILatLon other) {
078        return equalsEpsilon(other, MAX_SERVER_PRECISION);
079    }
080
081    /**
082     * Determines if the other point has almost the same lat/lon values.
083     * @param other other lat/lon
084     * @param precision The precision to use
085     * @return <code>true</code> if the other point has almost the same lat/lon
086     * values, only differing by no more than 1 / precision.
087     * @since 18464
088     */
089    default boolean equalsEpsilon(ILatLon other, double precision) {
090        double p = precision / 2;
091        return Math.abs(lat() - other.lat()) <= p && Math.abs(lon() - other.lon()) <= p;
092    }
093
094    /**
095     * Computes the distance between this lat/lon and another point on the earth.
096     * Uses <a href="https://en.wikipedia.org/wiki/Haversine_formula">Haversine formula</a>.
097     * @param other the other point.
098     * @return distance in metres.
099     * @since 18494
100     */
101    default double greatCircleDistance(ILatLon other) {
102        double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
103        double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
104        double d = 2 * WGS84.a * asin(
105                sqrt(sinHalfLat*sinHalfLat +
106                        cos(toRadians(this.lat()))*cos(toRadians(other.lat()))*sinHalfLon*sinHalfLon));
107        // For points opposite to each other on the sphere,
108        // rounding errors could make the argument of asin greater than 1
109        // (This should almost never happen.)
110        if (Double.isNaN(d)) {
111            Logging.error("NaN in greatCircleDistance: {0} {1}", this, other);
112            d = PI * WGS84.a;
113        }
114        return d;
115    }
116
117    /**
118     * Returns bearing from this point to another.
119     *
120     * Angle starts from north and increases clockwise, PI/2 means east.
121     *
122     * Please note that reverse bearing (from other point to this point) should NOT be
123     * calculated from return value of this method, because great circle path
124     * between the two points have different bearings at each position.
125     *
126     * To get bearing from another point to this point call other.bearing(this)
127     *
128     * @param other the "destination" position
129     * @return heading in radians in the range 0 &lt;= hd &lt; 2*PI
130     * @since 18494
131     */
132    default double bearing(ILatLon other) {
133        double lat1 = toRadians(this.lat());
134        double lat2 = toRadians(other.lat());
135        double dlon = toRadians(other.lon() - this.lon());
136        double bearing = atan2(
137                sin(dlon) * cos(lat2),
138                cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)
139        );
140        bearing %= 2 * PI;
141        if (bearing < 0) {
142            bearing += 2 * PI;
143        }
144        return bearing;
145    }
146
147    /**
148     * Does a linear interpolation between two ILatLon instances.
149     * @param ll2 The other ILatLon instance.
150     * @param proportion The proportion the other instance influences the result.
151     * @return The new {@link ILatLon} position.
152     * @since 18589
153     */
154    default ILatLon interpolate(ILatLon ll2, double proportion) {
155        // this is an alternate form of this.lat() + proportion * (ll2.lat() - this.lat()) that is slightly faster
156        return new LatLon((1 - proportion) * this.lat() + proportion * ll2.lat(),
157                (1 - proportion) * this.lon() + proportion * ll2.lon());
158    }
159
160    /**
161     * Returns the square of euclidean distance from this {@code Coordinate} to a specified coordinate.
162     *
163     * @param lon the X coordinate of the specified point to be measured against this {@code Coordinate}
164     * @param lat the Y coordinate of the specified point to be measured against this {@code Coordinate}
165     * @return the square of the euclidean distance from this {@code Coordinate} to a specified coordinate
166     * @since 18589
167     */
168    default double distanceSq(final double lon, final double lat) {
169        final double dx = this.lon() - lon;
170        final double dy = this.lat() - lat;
171        return dx * dx + dy * dy;
172    }
173
174    /**
175     * Returns the euclidean distance from this {@code ILatLon} to a specified {@code ILatLon}.
176     *
177     * @param other the specified coordinate to be measured against this {@code ILatLon}
178     * @return the euclidean distance from this {@code ILatLon} to a specified {@code ILatLon}
179     * @since 18589
180     */
181    default double distanceSq(final ILatLon other) {
182        return this.distanceSq(other.lon(), other.lat());
183    }
184}