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 java.lang.Math.toRadians;
011import static org.openstreetmap.josm.data.projection.Ellipsoid.WGS84;
012import static org.openstreetmap.josm.tools.I18n.trc;
013
014import java.awt.geom.Area;
015import java.text.DecimalFormat;
016import java.text.NumberFormat;
017import java.util.Arrays;
018import java.util.Locale;
019import java.util.Objects;
020
021import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
022import org.openstreetmap.josm.Main;
023import org.openstreetmap.josm.data.Bounds;
024import org.openstreetmap.josm.tools.Utils;
025
026/**
027 * LatLon are unprojected latitude / longitude coordinates.
028 * <br>
029 * <b>Latitude</b> specifies the north-south position in degrees
030 * where valid values are in the [-90,90] and positive values specify positions north of the equator.
031 * <br>
032 * <b>Longitude</b> specifies the east-west position in degrees
033 * where valid values are in the [-180,180] and positive values specify positions east of the prime meridian.
034 * <br>
035 * <img alt="lat/lon" src="https://upload.wikimedia.org/wikipedia/commons/6/62/Latitude_and_Longitude_of_the_Earth.svg">
036 * <br>
037 * This class is immutable.
038 *
039 * @author Imi
040 */
041public class LatLon extends Coordinate {
042
043    private static final long serialVersionUID = 1L;
044
045    /**
046     * Minimum difference in location to not be represented as the same position.
047     * The API returns 7 decimals.
048     */
049    public static final double MAX_SERVER_PRECISION = 1e-7;
050    public static final double MAX_SERVER_INV_PRECISION = 1e7;
051
052    /**
053     * The (0,0) coordinates.
054     * @since 6178
055     */
056    public static final LatLon ZERO = new LatLon(0, 0);
057
058    /** North pole. */
059    public static final LatLon NORTH_POLE = new LatLon(90, 0);
060    /** South pole. */
061    public static final LatLon SOUTH_POLE = new LatLon(-90, 0);
062
063    private static DecimalFormat cDmsMinuteFormatter = new DecimalFormat("00");
064    private static DecimalFormat cDmsSecondFormatter = new DecimalFormat(
065            Main.pref == null ? "00.0" : Main.pref.get("latlon.dms.decimal-format", "00.0"));
066    private static DecimalFormat cDmMinuteFormatter = new DecimalFormat(
067            Main.pref == null ? "00.000" : Main.pref.get("latlon.dm.decimal-format", "00.000"));
068    public static final DecimalFormat cDdFormatter;
069    public static final DecimalFormat cDdHighPecisionFormatter;
070    static {
071        // Don't use the localized decimal separator. This way we can present
072        // a comma separated list of coordinates.
073        cDdFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
074        cDdFormatter.applyPattern("###0.0######");
075        cDdHighPecisionFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
076        cDdHighPecisionFormatter.applyPattern("###0.0##########");
077    }
078
079    private static final String cDms60 = cDmsSecondFormatter.format(60.0);
080    private static final String cDms00 = cDmsSecondFormatter.format(0.0);
081    private static final String cDm60 = cDmMinuteFormatter.format(60.0);
082    private static final String cDm00 = cDmMinuteFormatter.format(0.0);
083
084    /**
085     * Replies true if lat is in the range [-90,90]
086     *
087     * @param lat the latitude
088     * @return true if lat is in the range [-90,90]
089     */
090    public static boolean isValidLat(double lat) {
091        return lat >= -90d && lat <= 90d;
092    }
093
094    /**
095     * Replies true if lon is in the range [-180,180]
096     *
097     * @param lon the longitude
098     * @return true if lon is in the range [-180,180]
099     */
100    public static boolean isValidLon(double lon) {
101        return lon >= -180d && lon <= 180d;
102    }
103
104    /**
105     * Make sure longitude value is within <code>[-180, 180]</code> range.
106     * @param lon the longitude in degrees
107     * @return lon plus/minus multiples of <code>360</code>, as needed to get
108     * in <code>[-180, 180]</code> range
109     */
110    public static double normalizeLon(double lon) {
111        if (lon >= -180 && lon <= 180)
112            return lon;
113        else {
114            lon = lon % 360.0;
115            if (lon > 180) {
116                return lon - 360;
117            } else if (lon < -180) {
118                return lon + 360;
119            }
120            return lon;
121        }
122    }
123
124    /**
125     * Replies true if lat is in the range [-90,90] and lon is in the range [-180,180]
126     *
127     * @return true if lat is in the range [-90,90] and lon is in the range [-180,180]
128     */
129    public boolean isValid() {
130        return isValidLat(lat()) && isValidLon(lon());
131    }
132
133    public static double toIntervalLat(double value) {
134        if (value < -90)
135            return -90;
136        if (value > 90)
137            return 90;
138        return value;
139    }
140
141    /**
142     * Returns a valid OSM longitude [-180,+180] for the given extended longitude value.
143     * For example, a value of -181 will return +179, a value of +181 will return -179.
144     * @param value A longitude value not restricted to the [-180,+180] range.
145     * @return a valid OSM longitude [-180,+180]
146     */
147    public static double toIntervalLon(double value) {
148        if (isValidLon(value))
149            return value;
150        else {
151            int n = (int) (value + Math.signum(value)*180.0) / 360;
152            return value - n*360.0;
153        }
154    }
155
156    /**
157     * Replies the coordinate in degrees/minutes/seconds format
158     * @param pCoordinate The coordinate to convert
159     * @return The coordinate in degrees/minutes/seconds format
160     */
161    public static String dms(double pCoordinate) {
162
163        double tAbsCoord = Math.abs(pCoordinate);
164        int tDegree = (int) tAbsCoord;
165        double tTmpMinutes = (tAbsCoord - tDegree) * 60;
166        int tMinutes = (int) tTmpMinutes;
167        double tSeconds = (tTmpMinutes - tMinutes) * 60;
168
169        String sDegrees = Integer.toString(tDegree);
170        String sMinutes = cDmsMinuteFormatter.format(tMinutes);
171        String sSeconds = cDmsSecondFormatter.format(tSeconds);
172
173        if (cDms60.equals(sSeconds)) {
174            sSeconds = cDms00;
175            sMinutes = cDmsMinuteFormatter.format(tMinutes+1L);
176        }
177        if ("60".equals(sMinutes)) {
178            sMinutes = "00";
179            sDegrees = Integer.toString(tDegree+1);
180        }
181
182        return sDegrees + '\u00B0' + sMinutes + '\'' + sSeconds + '\"';
183    }
184
185    /**
186     * Replies the coordinate in degrees/minutes format
187     * @param pCoordinate The coordinate to convert
188     * @return The coordinate in degrees/minutes format
189     */
190    public static String dm(double pCoordinate) {
191
192        double tAbsCoord = Math.abs(pCoordinate);
193        int tDegree = (int) tAbsCoord;
194        double tMinutes = (tAbsCoord - tDegree) * 60;
195
196        String sDegrees = Integer.toString(tDegree);
197        String sMinutes = cDmMinuteFormatter.format(tMinutes);
198
199        if (sMinutes.equals(cDm60)) {
200            sMinutes = cDm00;
201            sDegrees = Integer.toString(tDegree+1);
202        }
203
204        return sDegrees + '\u00B0' + sMinutes + '\'';
205    }
206
207    /**
208     * Constructs a new object representing the given latitude/longitude.
209     * @param lat the latitude, i.e., the north-south position in degrees
210     * @param lon the longitude, i.e., the east-west position in degrees
211     */
212    public LatLon(double lat, double lon) {
213        super(lon, lat);
214    }
215
216    protected LatLon(LatLon coor) {
217        super(coor.lon(), coor.lat());
218    }
219
220    /**
221     * Constructs a new object for the given coordinate
222     * @param coor the coordinate
223     */
224    public LatLon(ICoordinate coor) {
225        this(coor.getLat(), coor.getLon());
226    }
227
228    /**
229     * Returns the latitude, i.e., the north-south position in degrees.
230     * @return the latitude
231     */
232    public double lat() {
233        return y;
234    }
235
236    public static final String SOUTH = trc("compass", "S");
237    public static final String NORTH = trc("compass", "N");
238
239    /**
240     * Formats the latitude part according to the given format
241     * @param d the coordinate format to use
242     * @return the formatted latitude
243     */
244    public String latToString(CoordinateFormat d) {
245        switch(d) {
246        case DECIMAL_DEGREES: return cDdFormatter.format(y);
247        case DEGREES_MINUTES_SECONDS: return dms(y) + ((y < 0) ? SOUTH : NORTH);
248        case NAUTICAL: return dm(y) + ((y < 0) ? SOUTH : NORTH);
249        case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).north());
250        default: return "ERR";
251        }
252    }
253
254    /**
255     * Returns the longitude, i.e., the east-west position in degrees.
256     * @return the longitude
257     */
258    public double lon() {
259        return x;
260    }
261
262    public static final String WEST = trc("compass", "W");
263    public static final String EAST = trc("compass", "E");
264
265    /**
266     * Formats the longitude part according to the given format
267     * @param d the coordinate format to use
268     * @return the formatted longitude
269     */
270    public String lonToString(CoordinateFormat d) {
271        switch(d) {
272        case DECIMAL_DEGREES: return cDdFormatter.format(x);
273        case DEGREES_MINUTES_SECONDS: return dms(x) + ((x < 0) ? WEST : EAST);
274        case NAUTICAL: return dm(x) + ((x < 0) ? WEST : EAST);
275        case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).east());
276        default: return "ERR";
277        }
278    }
279
280    /**
281     * @param other other lat/lon
282     * @return <code>true</code> if the other point has almost the same lat/lon
283     * values, only differing by no more than 1 / {@link #MAX_SERVER_PRECISION MAX_SERVER_PRECISION}.
284     */
285    public boolean equalsEpsilon(LatLon other) {
286        double p = MAX_SERVER_PRECISION / 2;
287        return Math.abs(lat()-other.lat()) <= p && Math.abs(lon()-other.lon()) <= p;
288    }
289
290    /**
291     * Determines if this lat/lon is outside of the world
292     * @return <code>true</code>, if the coordinate is outside the world, compared by using lat/lon.
293     */
294    public boolean isOutSideWorld() {
295        Bounds b = Main.getProjection().getWorldBoundsLatLon();
296        return lat() < b.getMinLat() || lat() > b.getMaxLat() ||
297                lon() < b.getMinLon() || lon() > b.getMaxLon();
298    }
299
300    /**
301     * Determines if this lat/lon is within the given bounding box.
302     * @param b bounding box
303     * @return <code>true</code> if this is within the given bounding box.
304     */
305    public boolean isWithin(Bounds b) {
306        return b.contains(this);
307    }
308
309    /**
310     * Check if this is contained in given area or area is null.
311     *
312     * @param a Area
313     * @return <code>true</code> if this is contained in given area or area is null.
314     */
315    public boolean isIn(Area a) {
316        return a == null || a.contains(x, y);
317    }
318
319    /**
320     * Computes the distance between this lat/lon and another point on the earth.
321     * Uses Haversine formular.
322     * @param other the other point.
323     * @return distance in metres.
324     */
325    public double greatCircleDistance(LatLon other) {
326        double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
327        double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
328        double d = 2 * WGS84.a * asin(
329                sqrt(sinHalfLat*sinHalfLat +
330                        cos(toRadians(this.lat()))*cos(toRadians(other.lat()))*sinHalfLon*sinHalfLon));
331        // For points opposite to each other on the sphere,
332        // rounding errors could make the argument of asin greater than 1
333        // (This should almost never happen.)
334        if (java.lang.Double.isNaN(d)) {
335            Main.error("NaN in greatCircleDistance");
336            d = PI * WGS84.a;
337        }
338        return d;
339    }
340
341    /**
342     * Returns the heading that you have to use to get from this lat/lon to another.
343     *
344     * Angle starts from north and increases counterclockwise (!), PI/2 means west.
345     * You can get usual clockwise angle from {@link #bearing(LatLon)} method.
346     * This method is kept as deprecated because it is called from many plugins.
347     *
348     * (I don't know the original source of this formula, but see
349     * <a href="https://math.stackexchange.com/questions/720/how-to-calculate-a-heading-on-the-earths-surface">this question</a>
350     * for some hints how it is derived.)
351     *
352     * @deprecated see bearing method
353     * @param other the "destination" position
354     * @return heading in radians in the range 0 &lt;= hd &lt; 2*PI
355     */
356    @Deprecated
357    public double heading(LatLon other) {
358        double hd = atan2(sin(toRadians(this.lon() - other.lon())) * cos(toRadians(other.lat())),
359                cos(toRadians(this.lat())) * sin(toRadians(other.lat())) -
360                sin(toRadians(this.lat())) * cos(toRadians(other.lat())) * cos(toRadians(this.lon() - other.lon())));
361        hd %= 2 * PI;
362        if (hd < 0) {
363            hd += 2 * PI;
364        }
365        return hd;
366    }
367
368    /**
369     * Returns bearing from this point to another.
370     *
371     * Angle starts from north and increases clockwise, PI/2 means east.
372     * Old deprecated method {@link #heading(LatLon)} used unusual reverse angle.
373     *
374     * Please note that reverse bearing (from other point to this point) should NOT be
375     * calculated from return value of this method, because great circle path
376     * between the two points have different bearings at each position.
377     *
378     * To get bearing from another point to this point call other.bearing(this)
379     *
380     * @param other the "destination" position
381     * @return heading in radians in the range 0 &lt;= hd &lt; 2*PI
382     */
383    public double bearing(LatLon other) {
384        double lat1 = toRadians(this.lat());
385        double lat2 = toRadians(other.lat());
386        double dlon = toRadians(other.lon() - this.lon());
387        double bearing = atan2(
388            sin(dlon) * cos(lat2),
389            cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)
390        );
391        bearing %= 2 * PI;
392        if (bearing < 0) {
393            bearing += 2 * PI;
394        }
395        return bearing;
396    }
397
398    /**
399     * Returns this lat/lon pair in human-readable format.
400     *
401     * @return String in the format "lat=1.23456 deg, lon=2.34567 deg"
402     */
403    public String toDisplayString() {
404        NumberFormat nf = NumberFormat.getInstance();
405        nf.setMaximumFractionDigits(5);
406        return "lat=" + nf.format(lat()) + "\u00B0, lon=" + nf.format(lon()) + '\u00B0';
407    }
408
409    /**
410     * Returns this lat/lon pair in human-readable format separated by {@code separator}.
411     * @param separator values separator
412     * @return String in the format {@code "1.23456[separator]2.34567"}
413     */
414    public String toStringCSV(String separator) {
415        return Utils.join(separator, Arrays.asList(
416                latToString(CoordinateFormat.DECIMAL_DEGREES),
417                lonToString(CoordinateFormat.DECIMAL_DEGREES)
418        ));
419    }
420
421    public LatLon interpolate(LatLon ll2, double proportion) {
422        return new LatLon(this.lat() + proportion * (ll2.lat() - this.lat()),
423                this.lon() + proportion * (ll2.lon() - this.lon()));
424    }
425
426    public LatLon getCenter(LatLon ll2) {
427        return new LatLon((this.lat() + ll2.lat())/2.0, (this.lon() + ll2.lon())/2.0);
428    }
429
430    /**
431     * Returns the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
432     *
433     * @param ll the specified coordinate to be measured against this {@code LatLon}
434     * @return the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
435     * @since 6166
436     */
437    public double distance(final LatLon ll) {
438        return super.distance(ll);
439    }
440
441    /**
442     * Returns the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
443     *
444     * @param ll the specified coordinate to be measured against this {@code LatLon}
445     * @return the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
446     * @since 6166
447     */
448    public double distanceSq(final LatLon ll) {
449        return super.distanceSq(ll);
450    }
451
452    @Override
453    public String toString() {
454        return "LatLon[lat="+lat()+",lon="+lon()+']';
455    }
456
457    /**
458     * Returns the value rounded to OSM precisions, i.e. to {@link #MAX_SERVER_PRECISION}.
459     * @param value lat/lon value
460     *
461     * @return rounded value
462     */
463    public static double roundToOsmPrecision(double value) {
464        return Math.round(value * MAX_SERVER_INV_PRECISION) / MAX_SERVER_INV_PRECISION;
465    }
466
467    /**
468     * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to {@link #MAX_SERVER_PRECISION}
469     *
470     * @return a clone of this lat LatLon
471     */
472    public LatLon getRoundedToOsmPrecision() {
473        return new LatLon(
474                roundToOsmPrecision(lat()),
475                roundToOsmPrecision(lon())
476                );
477    }
478
479    @Override
480    public int hashCode() {
481        return Objects.hash(x, y);
482    }
483
484    @Override
485    public boolean equals(Object obj) {
486        if (this == obj) return true;
487        if (obj == null || getClass() != obj.getClass()) return false;
488        LatLon that = (LatLon) obj;
489        return Double.compare(that.x, x) == 0 &&
490               Double.compare(that.y, y) == 0;
491    }
492
493    /**
494     * Converts this latitude/longitude to an instance of {@link ICoordinate}.
495     * @return a {@link ICoordinate} instance of this latitude/longitude
496     */
497    public ICoordinate toCoordinate() {
498        return new org.openstreetmap.gui.jmapviewer.Coordinate(lat(), lon());
499    }
500}