source: josm/trunk/src/org/openstreetmap/josm/data/coor/LatLon.java@ 9862

Last change on this file since 9862 was 9862, checked in by simon04, 8 years ago

fix #12563 - Allow to customize LatLon formatting

Use the preference keys latlon.dms.decimal-format and
latlon.dm.decimal-format.

  • Property svn:eol-style set to native
File size: 18.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.coor;
3
4import static java.lang.Math.PI;
5import static java.lang.Math.asin;
6import static java.lang.Math.atan2;
7import static java.lang.Math.cos;
8import static java.lang.Math.sin;
9import static java.lang.Math.sqrt;
10import static java.lang.Math.toRadians;
11import static org.openstreetmap.josm.tools.I18n.trc;
12
13import java.awt.geom.Area;
14import java.text.DecimalFormat;
15import java.text.NumberFormat;
16import java.util.Arrays;
17import java.util.Locale;
18import java.util.Objects;
19
20import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.data.Bounds;
23import org.openstreetmap.josm.tools.Utils;
24
25/**
26 * LatLon are unprojected latitude / longitude coordinates.
27 * <br>
28 * <b>Latitude</b> specifies the north-south position in degrees
29 * where valid values are in the [-90,90] and positive values specify positions north of the equator.
30 * <br>
31 * <b>Longitude</b> specifies the east-west position in degrees
32 * where valid values are in the [-180,180] and positive values specify positions east of the prime meridian.
33 * <br>
34 * <img alt="lat/lon" src="https://upload.wikimedia.org/wikipedia/commons/6/62/Latitude_and_Longitude_of_the_Earth.svg">
35 * <br>
36 * This class is immutable.
37 *
38 * @author Imi
39 */
40public class LatLon extends Coordinate {
41
42 private static final long serialVersionUID = 1L;
43
44 /**
45 * Minimum difference in location to not be represented as the same position.
46 * The API returns 7 decimals.
47 */
48 public static final double MAX_SERVER_PRECISION = 1e-7;
49 public static final double MAX_SERVER_INV_PRECISION = 1e7;
50 public static final int MAX_SERVER_DIGITS = 7;
51
52 /**
53 * The (0,0) coordinates.
54 * @since 6178
55 */
56 public static final LatLon ZERO = new LatLon(0, 0);
57
58 /**
59 * North and south pole.
60 */
61 public static final LatLon NORTH_POLE = new LatLon(90, 0);
62 public static final LatLon SOUTH_POLE = new LatLon(-90, 0);
63
64 private static DecimalFormat cDmsMinuteFormatter = new DecimalFormat("00");
65 private static DecimalFormat cDmsSecondFormatter = new DecimalFormat(Main.pref.get("latlon.dms.decimal-format", "00.0"));
66 private static DecimalFormat cDmMinuteFormatter = new DecimalFormat(Main.pref.get("latlon.dm.decimal-format", "00.000"));
67 public static final DecimalFormat cDdFormatter;
68 public static final DecimalFormat cDdHighPecisionFormatter;
69 static {
70 // Don't use the localized decimal separator. This way we can present
71 // a comma separated list of coordinates.
72 cDdFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
73 cDdFormatter.applyPattern("###0.0######");
74 cDdHighPecisionFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
75 cDdHighPecisionFormatter.applyPattern("###0.0##########");
76 }
77
78 private static final String cDms60 = cDmsSecondFormatter.format(60.0);
79 private static final String cDms00 = cDmsSecondFormatter.format(0.0);
80 private static final String cDm60 = cDmMinuteFormatter.format(60.0);
81 private static final String cDm00 = cDmMinuteFormatter.format(0.0);
82
83 /**
84 * Replies true if lat is in the range [-90,90]
85 *
86 * @param lat the latitude
87 * @return true if lat is in the range [-90,90]
88 */
89 public static boolean isValidLat(double lat) {
90 return lat >= -90d && lat <= 90d;
91 }
92
93 /**
94 * Replies true if lon is in the range [-180,180]
95 *
96 * @param lon the longitude
97 * @return true if lon is in the range [-180,180]
98 */
99 public static boolean isValidLon(double lon) {
100 return lon >= -180d && lon <= 180d;
101 }
102
103 /**
104 * Make sure longitude value is within <code>[-180, 180]</code> range.
105 * @param lon the longitude in degrees
106 * @return lon plus/minus multiples of <code>360</code>, as needed to get
107 * in <code>[-180, 180]</code> range
108 */
109 public static double normalizeLon(double lon) {
110 if (lon >= -180 && lon <= 180)
111 return lon;
112 else {
113 lon = lon % 360.0;
114 if (lon > 180) {
115 return lon - 360;
116 } else if (lon < -180) {
117 return lon + 360;
118 }
119 return lon;
120 }
121 }
122
123 /**
124 * Replies true if lat is in the range [-90,90] and lon is in the range [-180,180]
125 *
126 * @return true if lat is in the range [-90,90] and lon is in the range [-180,180]
127 */
128 public boolean isValid() {
129 return isValidLat(lat()) && isValidLon(lon());
130 }
131
132 public static double toIntervalLat(double value) {
133 if (value < -90)
134 return -90;
135 if (value > 90)
136 return 90;
137 return value;
138 }
139
140 /**
141 * Returns a valid OSM longitude [-180,+180] for the given extended longitude value.
142 * For example, a value of -181 will return +179, a value of +181 will return -179.
143 * @param value A longitude value not restricted to the [-180,+180] range.
144 * @return a valid OSM longitude [-180,+180]
145 */
146 public static double toIntervalLon(double value) {
147 if (isValidLon(value))
148 return value;
149 else {
150 int n = (int) (value + Math.signum(value)*180.0) / 360;
151 return value - n*360.0;
152 }
153 }
154
155 /**
156 * Replies the coordinate in degrees/minutes/seconds format
157 * @param pCoordinate The coordinate to convert
158 * @return The coordinate in degrees/minutes/seconds format
159 */
160 public static String dms(double pCoordinate) {
161
162 double tAbsCoord = Math.abs(pCoordinate);
163 int tDegree = (int) tAbsCoord;
164 double tTmpMinutes = (tAbsCoord - tDegree) * 60;
165 int tMinutes = (int) tTmpMinutes;
166 double tSeconds = (tTmpMinutes - tMinutes) * 60;
167
168 String sDegrees = Integer.toString(tDegree);
169 String sMinutes = cDmsMinuteFormatter.format(tMinutes);
170 String sSeconds = cDmsSecondFormatter.format(tSeconds);
171
172 if (cDms60.equals(sSeconds)) {
173 sSeconds = cDms00;
174 sMinutes = cDmsMinuteFormatter.format(tMinutes+1);
175 }
176 if ("60".equals(sMinutes)) {
177 sMinutes = "00";
178 sDegrees = Integer.toString(tDegree+1);
179 }
180
181 return sDegrees + '\u00B0' + sMinutes + '\'' + sSeconds + '\"';
182 }
183
184 /**
185 * Replies the coordinate in degrees/minutes format
186 * @param pCoordinate The coordinate to convert
187 * @return The coordinate in degrees/minutes format
188 */
189 public static String dm(double pCoordinate) {
190
191 double tAbsCoord = Math.abs(pCoordinate);
192 int tDegree = (int) tAbsCoord;
193 double tMinutes = (tAbsCoord - tDegree) * 60;
194
195 String sDegrees = Integer.toString(tDegree);
196 String sMinutes = cDmMinuteFormatter.format(tMinutes);
197
198 if (sMinutes.equals(cDm60)) {
199 sMinutes = cDm00;
200 sDegrees = Integer.toString(tDegree+1);
201 }
202
203 return sDegrees + '\u00B0' + sMinutes + '\'';
204 }
205
206 /**
207 * Constructs a new object representing the given latitude/longitude.
208 * @param lat the latitude, i.e., the north-south position in degrees
209 * @param lon the longitude, i.e., the east-west position in degrees
210 */
211 public LatLon(double lat, double lon) {
212 super(lon, lat);
213 }
214
215 protected LatLon(LatLon coor) {
216 super(coor.lon(), coor.lat());
217 }
218
219 /**
220 * Constructs a new object for the given coordinate
221 * @param coor the coordinate
222 */
223 public LatLon(ICoordinate coor) {
224 this(coor.getLat(), coor.getLon());
225 }
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 R = 6378135;
327 double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
328 double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
329 double d = 2 * R * asin(
330 sqrt(sinHalfLat*sinHalfLat +
331 cos(toRadians(this.lat()))*cos(toRadians(other.lat()))*sinHalfLon*sinHalfLon));
332 // For points opposite to each other on the sphere,
333 // rounding errors could make the argument of asin greater than 1
334 // (This should almost never happen.)
335 if (java.lang.Double.isNaN(d)) {
336 Main.error("NaN in greatCircleDistance");
337 d = PI * R;
338 }
339 return d;
340 }
341
342 /**
343 * Returns the heading that you have to use to get from this lat/lon to another.
344 *
345 * Angle starts from north and increases counterclockwise (!), PI/2 means west.
346 * You can get usual clockwise angle from {@link #bearing(LatLon)} method.
347 * This method is kept as deprecated because it is called from many plugins.
348 *
349 * (I don't know the original source of this formula, but see
350 * <a href="https://math.stackexchange.com/questions/720/how-to-calculate-a-heading-on-the-earths-surface">this question</a>
351 * for some hints how it is derived.)
352 *
353 * @deprecated see bearing method
354 * @param other the "destination" position
355 * @return heading in radians in the range 0 &lt;= hd &lt; 2*PI
356 */
357 @Deprecated
358 public double heading(LatLon other) {
359 double hd = atan2(sin(toRadians(this.lon() - other.lon())) * cos(toRadians(other.lat())),
360 cos(toRadians(this.lat())) * sin(toRadians(other.lat())) -
361 sin(toRadians(this.lat())) * cos(toRadians(other.lat())) * cos(toRadians(this.lon() - other.lon())));
362 hd %= 2 * PI;
363 if (hd < 0) {
364 hd += 2 * PI;
365 }
366 return hd;
367 }
368
369 /**
370 * Returns bearing from this point to another.
371 *
372 * Angle starts from north and increases clockwise, PI/2 means east.
373 * Old deprecated method {@link #heading(LatLon)} used unusual reverse angle.
374 *
375 * Please note that reverse bearing (from other point to this point) should NOT be
376 * calculated from return value of this method, because great circle path
377 * between the two points have different bearings at each position.
378 *
379 * To get bearing from another point to this point call other.bearing(this)
380 *
381 * @param other the "destination" position
382 * @return heading in radians in the range 0 &lt;= hd &lt; 2*PI
383 */
384 public double bearing(LatLon other) {
385 double lat1 = toRadians(this.lat());
386 double lat2 = toRadians(other.lat());
387 double dlon = toRadians(other.lon() - this.lon());
388 double bearing = atan2(
389 sin(dlon) * cos(lat2),
390 cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)
391 );
392 bearing %= 2 * PI;
393 if (bearing < 0) {
394 bearing += 2 * PI;
395 }
396 return bearing;
397 }
398
399 /**
400 * Returns this lat/lon pair in human-readable format.
401 *
402 * @return String in the format "lat=1.23456 deg, lon=2.34567 deg"
403 */
404 public String toDisplayString() {
405 NumberFormat nf = NumberFormat.getInstance();
406 nf.setMaximumFractionDigits(5);
407 return "lat=" + nf.format(lat()) + "\u00B0, lon=" + nf.format(lon()) + '\u00B0';
408 }
409
410 /**
411 * Returns this lat/lon pair in human-readable format separated by {@code separator}.
412 * @param separator values separator
413 * @return String in the format {@code "1.23456[separator]2.34567"}
414 */
415 public String toStringCSV(String separator) {
416 return Utils.join(separator, Arrays.asList(
417 latToString(CoordinateFormat.DECIMAL_DEGREES),
418 lonToString(CoordinateFormat.DECIMAL_DEGREES)
419 ));
420 }
421
422 public LatLon interpolate(LatLon ll2, double proportion) {
423 return new LatLon(this.lat() + proportion * (ll2.lat() - this.lat()),
424 this.lon() + proportion * (ll2.lon() - this.lon()));
425 }
426
427 public LatLon getCenter(LatLon ll2) {
428 return new LatLon((this.lat() + ll2.lat())/2.0, (this.lon() + ll2.lon())/2.0);
429 }
430
431 /**
432 * Returns the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
433 *
434 * @param ll the specified coordinate to be measured against this {@code LatLon}
435 * @return the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
436 * @since 6166
437 */
438 public double distance(final LatLon ll) {
439 return super.distance(ll);
440 }
441
442 /**
443 * Returns the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
444 *
445 * @param ll the specified coordinate to be measured against this {@code LatLon}
446 * @return the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
447 * @since 6166
448 */
449 public double distanceSq(final LatLon ll) {
450 return super.distanceSq(ll);
451 }
452
453 @Override
454 public String toString() {
455 return "LatLon[lat="+lat()+",lon="+lon()+']';
456 }
457
458 /**
459 * Returns the value rounded to OSM precisions, i.e. to {@link LatLon#MAX_SERVER_PRECISION}.
460 * @param value lat/lon value
461 *
462 * @return rounded value
463 */
464 public static double roundToOsmPrecision(double value) {
465 return Math.round(value * MAX_SERVER_INV_PRECISION) / MAX_SERVER_INV_PRECISION;
466 }
467
468 /**
469 * Returns the value rounded to OSM precision. This function is now the same as
470 * {@link #roundToOsmPrecision(double)}, since the rounding error has been fixed.
471 * @param value lat/lon value
472 *
473 * @return rounded value
474 * @deprecated Use {@link #roundToOsmPrecision(double)} instead
475 */
476 @Deprecated
477 public static double roundToOsmPrecisionStrict(double value) {
478 return roundToOsmPrecision(value);
479 }
480
481 /**
482 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
483 * MAX_SERVER_PRECISION
484 *
485 * @return a clone of this lat LatLon
486 */
487 public LatLon getRoundedToOsmPrecision() {
488 return new LatLon(
489 roundToOsmPrecision(lat()),
490 roundToOsmPrecision(lon())
491 );
492 }
493
494 /**
495 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
496 * MAX_SERVER_PRECISION
497 *
498 * @return a clone of this lat LatLon
499 * @deprecated Use {@link #getRoundedToOsmPrecision()} instead
500 */
501 @Deprecated
502 public LatLon getRoundedToOsmPrecisionStrict() {
503 return getRoundedToOsmPrecision();
504 }
505
506 @Override
507 public int hashCode() {
508 return Objects.hash(x, y);
509 }
510
511 @Override
512 public boolean equals(Object obj) {
513 if (this == obj) return true;
514 if (!(obj instanceof LatLon)) return false;
515 LatLon that = (LatLon) obj;
516 return Double.compare(that.x, x) == 0 &&
517 Double.compare(that.y, y) == 0;
518 }
519
520 /**
521 * Converts this latitude/longitude to an instance of {@link ICoordinate}.
522 * @return a {@link ICoordinate} instance of this latitude/longitude
523 */
524 public ICoordinate toCoordinate() {
525 return new org.openstreetmap.gui.jmapviewer.Coordinate(lat(), lon());
526 }
527}
Note: See TracBrowser for help on using the repository browser.