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