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.tools.I18n.trc;
012
013import java.awt.geom.Area;
014import java.text.DecimalFormat;
015import java.text.NumberFormat;
016import java.util.Arrays;
017import java.util.Locale;
018import java.util.Objects;
019
020import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
021import org.openstreetmap.josm.Main;
022import org.openstreetmap.josm.data.Bounds;
023import org.openstreetmap.josm.tools.Utils;
024
025/**
026 * LatLon are unprojected latitude / longitude coordinates.
027 * <br>
028 * <b>Latitude</b> specifies the north-south position in degrees
029 * where valid values are in the [-90,90] and positive values specify positions north of the equator.
030 * <br>
031 * <b>Longitude</b> specifies the east-west position in degrees
032 * where valid values are in the [-180,180] and positive values specify positions east of the prime meridian.
033 * <br>
034 * <img alt="lat/lon" src="https://upload.wikimedia.org/wikipedia/commons/6/62/Latitude_and_Longitude_of_the_Earth.svg">
035 * <br>
036 * This class is immutable.
037 *
038 * @author Imi
039 */
040public class LatLon extends Coordinate {
041
042    private static final long serialVersionUID = 1L;
043
044    /**
045     * Minimum difference in location to not be represented as the same position.
046     * The API returns 7 decimals.
047     */
048    public static final double MAX_SERVER_PRECISION = 1e-7;
049    public static final double MAX_SERVER_INV_PRECISION = 1e7;
050    public static final int    MAX_SERVER_DIGITS = 7;
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+1);
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 R = 6378135;
329        double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
330        double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
331        double d = 2 * R * asin(
332                sqrt(sinHalfLat*sinHalfLat +
333                        cos(toRadians(this.lat()))*cos(toRadians(other.lat()))*sinHalfLon*sinHalfLon));
334        // For points opposite to each other on the sphere,
335        // rounding errors could make the argument of asin greater than 1
336        // (This should almost never happen.)
337        if (java.lang.Double.isNaN(d)) {
338            Main.error("NaN in greatCircleDistance");
339            d = PI * R;
340        }
341        return d;
342    }
343
344    /**
345     * Returns the heading that you have to use to get from this lat/lon to another.
346     *
347     * Angle starts from north and increases counterclockwise (!), PI/2 means west.
348     * You can get usual clockwise angle from {@link #bearing(LatLon)} method.
349     * This method is kept as deprecated because it is called from many plugins.
350     *
351     * (I don't know the original source of this formula, but see
352     * <a href="https://math.stackexchange.com/questions/720/how-to-calculate-a-heading-on-the-earths-surface">this question</a>
353     * for some hints how it is derived.)
354     *
355     * @deprecated see bearing method
356     * @param other the "destination" position
357     * @return heading in radians in the range 0 &lt;= hd &lt; 2*PI
358     */
359    @Deprecated
360    public double heading(LatLon other) {
361        double hd = atan2(sin(toRadians(this.lon() - other.lon())) * cos(toRadians(other.lat())),
362                cos(toRadians(this.lat())) * sin(toRadians(other.lat())) -
363                sin(toRadians(this.lat())) * cos(toRadians(other.lat())) * cos(toRadians(this.lon() - other.lon())));
364        hd %= 2 * PI;
365        if (hd < 0) {
366            hd += 2 * PI;
367        }
368        return hd;
369    }
370
371    /**
372     * Returns bearing from this point to another.
373     *
374     * Angle starts from north and increases clockwise, PI/2 means east.
375     * Old deprecated method {@link #heading(LatLon)} used unusual reverse angle.
376     *
377     * Please note that reverse bearing (from other point to this point) should NOT be
378     * calculated from return value of this method, because great circle path
379     * between the two points have different bearings at each position.
380     *
381     * To get bearing from another point to this point call other.bearing(this)
382     *
383     * @param other the "destination" position
384     * @return heading in radians in the range 0 &lt;= hd &lt; 2*PI
385     */
386    public double bearing(LatLon other) {
387        double lat1 = toRadians(this.lat());
388        double lat2 = toRadians(other.lat());
389        double dlon = toRadians(other.lon() - this.lon());
390        double bearing = atan2(
391            sin(dlon) * cos(lat2),
392            cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)
393        );
394        bearing %= 2 * PI;
395        if (bearing < 0) {
396            bearing += 2 * PI;
397        }
398        return bearing;
399    }
400
401    /**
402     * Returns this lat/lon pair in human-readable format.
403     *
404     * @return String in the format "lat=1.23456 deg, lon=2.34567 deg"
405     */
406    public String toDisplayString() {
407        NumberFormat nf = NumberFormat.getInstance();
408        nf.setMaximumFractionDigits(5);
409        return "lat=" + nf.format(lat()) + "\u00B0, lon=" + nf.format(lon()) + '\u00B0';
410    }
411
412    /**
413     * Returns this lat/lon pair in human-readable format separated by {@code separator}.
414     * @param separator values separator
415     * @return String in the format {@code "1.23456[separator]2.34567"}
416     */
417    public String toStringCSV(String separator) {
418        return Utils.join(separator, Arrays.asList(
419                latToString(CoordinateFormat.DECIMAL_DEGREES),
420                lonToString(CoordinateFormat.DECIMAL_DEGREES)
421        ));
422    }
423
424    public LatLon interpolate(LatLon ll2, double proportion) {
425        return new LatLon(this.lat() + proportion * (ll2.lat() - this.lat()),
426                this.lon() + proportion * (ll2.lon() - this.lon()));
427    }
428
429    public LatLon getCenter(LatLon ll2) {
430        return new LatLon((this.lat() + ll2.lat())/2.0, (this.lon() + ll2.lon())/2.0);
431    }
432
433    /**
434     * Returns the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
435     *
436     * @param ll the specified coordinate to be measured against this {@code LatLon}
437     * @return the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
438     * @since 6166
439     */
440    public double distance(final LatLon ll) {
441        return super.distance(ll);
442    }
443
444    /**
445     * Returns the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
446     *
447     * @param ll the specified coordinate to be measured against this {@code LatLon}
448     * @return the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
449     * @since 6166
450     */
451    public double distanceSq(final LatLon ll) {
452        return super.distanceSq(ll);
453    }
454
455    @Override
456    public String toString() {
457        return "LatLon[lat="+lat()+",lon="+lon()+']';
458    }
459
460    /**
461     * Returns the value rounded to OSM precisions, i.e. to {@link LatLon#MAX_SERVER_PRECISION}.
462     * @param value lat/lon value
463     *
464     * @return rounded value
465     */
466    public static double roundToOsmPrecision(double value) {
467        return Math.round(value * MAX_SERVER_INV_PRECISION) / MAX_SERVER_INV_PRECISION;
468    }
469
470    /**
471     * Returns the value rounded to OSM precision. This function is now the same as
472     * {@link #roundToOsmPrecision(double)}, since the rounding error has been fixed.
473     * @param value lat/lon value
474     *
475     * @return rounded value
476     * @deprecated Use {@link #roundToOsmPrecision(double)} instead
477     */
478    @Deprecated
479    public static double roundToOsmPrecisionStrict(double value) {
480        return roundToOsmPrecision(value);
481    }
482
483    /**
484     * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
485     * MAX_SERVER_PRECISION
486     *
487     * @return a clone of this lat LatLon
488     */
489    public LatLon getRoundedToOsmPrecision() {
490        return new LatLon(
491                roundToOsmPrecision(lat()),
492                roundToOsmPrecision(lon())
493                );
494    }
495
496    /**
497     * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
498     * MAX_SERVER_PRECISION
499     *
500     * @return a clone of this lat LatLon
501     * @deprecated Use {@link #getRoundedToOsmPrecision()} instead
502     */
503    @Deprecated
504    public LatLon getRoundedToOsmPrecisionStrict() {
505        return getRoundedToOsmPrecision();
506    }
507
508    @Override
509    public int hashCode() {
510        return Objects.hash(x, y);
511    }
512
513    @Override
514    public boolean equals(Object obj) {
515        if (this == obj) return true;
516        if (!(obj instanceof LatLon)) return false;
517        LatLon that = (LatLon) obj;
518        return Double.compare(that.x, x) == 0 &&
519                Double.compare(that.y, y) == 0;
520    }
521
522    /**
523     * Converts this latitude/longitude to an instance of {@link ICoordinate}.
524     * @return a {@link ICoordinate} instance of this latitude/longitude
525     */
526    public ICoordinate toCoordinate() {
527        return new org.openstreetmap.gui.jmapviewer.Coordinate(lat(), lon());
528    }
529}