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

Last change on this file since 10915 was 10915, checked in by michael2402, 8 years ago

Trim interpolate in EastNorth/LatLon for performance and add comment explaining it. Added unit tests.

  • Property svn:eol-style set to native
File size: 18.1 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.data.projection.Ellipsoid.WGS84;
12import static org.openstreetmap.josm.tools.I18n.trc;
13
14import java.awt.geom.Area;
15import java.text.DecimalFormat;
16import java.text.NumberFormat;
17import java.util.Arrays;
18import java.util.Locale;
19import java.util.Objects;
20
21import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.data.Bounds;
24import org.openstreetmap.josm.tools.Utils;
25
26/**
27 * LatLon are unprojected latitude / longitude coordinates.
28 * <br>
29 * <b>Latitude</b> specifies the north-south position in degrees
30 * where valid values are in the [-90,90] and positive values specify positions north of the equator.
31 * <br>
32 * <b>Longitude</b> specifies the east-west position in degrees
33 * where valid values are in the [-180,180] and positive values specify positions east of the prime meridian.
34 * <br>
35 * <img alt="lat/lon" src="https://upload.wikimedia.org/wikipedia/commons/6/62/Latitude_and_Longitude_of_the_Earth.svg">
36 * <br>
37 * This class is immutable.
38 *
39 * @author Imi
40 */
41public class LatLon extends Coordinate {
42
43 private static final long serialVersionUID = 1L;
44
45 /**
46 * Minimum difference in location to not be represented as the same position.
47 * The API returns 7 decimals.
48 */
49 public static final double MAX_SERVER_PRECISION = 1e-7;
50 public static final double MAX_SERVER_INV_PRECISION = 1e7;
51
52 /**
53 * The (0,0) coordinates.
54 * @since 6178
55 */
56 public static final LatLon ZERO = new LatLon(0, 0);
57
58 /** North pole. */
59 public static final LatLon NORTH_POLE = new LatLon(90, 0);
60 /** South pole. */
61 public static final LatLon SOUTH_POLE = new LatLon(-90, 0);
62
63 private static DecimalFormat cDmsMinuteFormatter = new DecimalFormat("00");
64 private static DecimalFormat cDmsSecondFormatter = new DecimalFormat(
65 Main.pref == null ? "00.0" : Main.pref.get("latlon.dms.decimal-format", "00.0"));
66 private static DecimalFormat cDmMinuteFormatter = new DecimalFormat(
67 Main.pref == null ? "00.000" : Main.pref.get("latlon.dm.decimal-format", "00.000"));
68 public static final DecimalFormat cDdFormatter;
69 public static final DecimalFormat cDdHighPecisionFormatter;
70 static {
71 // Don't use the localized decimal separator. This way we can present
72 // a comma separated list of coordinates.
73 cDdFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
74 cDdFormatter.applyPattern("###0.0######");
75 cDdHighPecisionFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
76 cDdHighPecisionFormatter.applyPattern("###0.0##########");
77 }
78
79 private static final String cDms60 = cDmsSecondFormatter.format(60.0);
80 private static final String cDms00 = cDmsSecondFormatter.format(0.0);
81 private static final String cDm60 = cDmMinuteFormatter.format(60.0);
82 private static final String cDm00 = cDmMinuteFormatter.format(0.0);
83
84 /**
85 * Replies true if lat is in the range [-90,90]
86 *
87 * @param lat the latitude
88 * @return true if lat is in the range [-90,90]
89 */
90 public static boolean isValidLat(double lat) {
91 return lat >= -90d && lat <= 90d;
92 }
93
94 /**
95 * Replies true if lon is in the range [-180,180]
96 *
97 * @param lon the longitude
98 * @return true if lon is in the range [-180,180]
99 */
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 /**
134 * Clamp the lat value to be inside the world.
135 * @param value The value
136 * @return The value clamped to the world.
137 */
138 public static double toIntervalLat(double value) {
139 return Utils.clamp(value, -90, 90);
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 * Returns the latitude, i.e., the north-south position in degrees.
231 * @return the latitude
232 */
233 public double lat() {
234 return y;
235 }
236
237 public static final String SOUTH = trc("compass", "S");
238 public static final String NORTH = trc("compass", "N");
239
240 /**
241 * Formats the latitude part according to the given format
242 * @param d the coordinate format to use
243 * @return the formatted latitude
244 */
245 public String latToString(CoordinateFormat d) {
246 switch(d) {
247 case DECIMAL_DEGREES: return cDdFormatter.format(y);
248 case DEGREES_MINUTES_SECONDS: return dms(y) + ((y < 0) ? SOUTH : NORTH);
249 case NAUTICAL: return dm(y) + ((y < 0) ? SOUTH : NORTH);
250 case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).north());
251 default: return "ERR";
252 }
253 }
254
255 /**
256 * Returns the longitude, i.e., the east-west position in degrees.
257 * @return the longitude
258 */
259 public double lon() {
260 return x;
261 }
262
263 public static final String WEST = trc("compass", "W");
264 public static final String EAST = trc("compass", "E");
265
266 /**
267 * Formats the longitude part according to the given format
268 * @param d the coordinate format to use
269 * @return the formatted longitude
270 */
271 public String lonToString(CoordinateFormat d) {
272 switch(d) {
273 case DECIMAL_DEGREES: return cDdFormatter.format(x);
274 case DEGREES_MINUTES_SECONDS: return dms(x) + ((x < 0) ? WEST : EAST);
275 case NAUTICAL: return dm(x) + ((x < 0) ? WEST : EAST);
276 case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).east());
277 default: return "ERR";
278 }
279 }
280
281 /**
282 * @param other other lat/lon
283 * @return <code>true</code> if the other point has almost the same lat/lon
284 * values, only differing by no more than 1 / {@link #MAX_SERVER_PRECISION MAX_SERVER_PRECISION}.
285 */
286 public boolean equalsEpsilon(LatLon other) {
287 double p = MAX_SERVER_PRECISION / 2;
288 return Math.abs(lat()-other.lat()) <= p && Math.abs(lon()-other.lon()) <= p;
289 }
290
291 /**
292 * Determines if this lat/lon is outside of the world
293 * @return <code>true</code>, if the coordinate is outside the world, compared by using lat/lon.
294 */
295 public boolean isOutSideWorld() {
296 Bounds b = Main.getProjection().getWorldBoundsLatLon();
297 return lat() < b.getMinLat() || lat() > b.getMaxLat() ||
298 lon() < b.getMinLon() || lon() > b.getMaxLon();
299 }
300
301 /**
302 * Determines if this lat/lon is within the given bounding box.
303 * @param b bounding box
304 * @return <code>true</code> if this is within the given bounding box.
305 */
306 public boolean isWithin(Bounds b) {
307 return b.contains(this);
308 }
309
310 /**
311 * Check if this is contained in given area or area is null.
312 *
313 * @param a Area
314 * @return <code>true</code> if this is contained in given area or area is null.
315 */
316 public boolean isIn(Area a) {
317 return a == null || a.contains(x, y);
318 }
319
320 /**
321 * Computes the distance between this lat/lon and another point on the earth.
322 * Uses Haversine formular.
323 * @param other the other point.
324 * @return distance in metres.
325 */
326 public double greatCircleDistance(LatLon other) {
327 double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
328 double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
329 double d = 2 * WGS84.a * 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 * WGS84.a;
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 /**
423 * Interpolate between this and a other latlon
424 * @param ll2 The other lat/lon object
425 * @param proportion The proportion to interpolate
426 * @return a new latlon at this position if proportion is 0, at the other position it proportion is 1 and lineary interpolated otherwise.
427 */
428 public LatLon interpolate(LatLon ll2, double proportion) {
429 // this is an alternate form of this.lat() + proportion * (ll2.lat() - this.lat()) that is slightly faster
430 return new LatLon((1 - proportion) * this.lat() + proportion * ll2.lat(),
431 (1 - proportion) * this.lon() + proportion * ll2.lon());
432 }
433
434 /**
435 * Get the center between two lat/lon points
436 * @param ll2 The other {@link LatLon}
437 * @return The center at the average coordinates of the two points. Does not take the 180° meridian into account.
438 */
439 public LatLon getCenter(LatLon ll2) {
440 // The JIT will inline this for us, it is as fast as the normal /2 approach
441 return interpolate(ll2, .5);
442 }
443
444 /**
445 * Returns 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 euclidean distance from this {@code LatLon} to a specified {@code LatLon}
449 * @since 6166
450 */
451 public double distance(final LatLon ll) {
452 return super.distance(ll);
453 }
454
455 /**
456 * Returns the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
457 *
458 * @param ll the specified coordinate to be measured against this {@code LatLon}
459 * @return the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
460 * @since 6166
461 */
462 public double distanceSq(final LatLon ll) {
463 return super.distanceSq(ll);
464 }
465
466 @Override
467 public String toString() {
468 return "LatLon[lat="+lat()+",lon="+lon()+']';
469 }
470
471 /**
472 * Returns the value rounded to OSM precisions, i.e. to {@link #MAX_SERVER_PRECISION}.
473 * @param value lat/lon value
474 *
475 * @return rounded value
476 */
477 public static double roundToOsmPrecision(double value) {
478 return Math.round(value * MAX_SERVER_INV_PRECISION) / MAX_SERVER_INV_PRECISION;
479 }
480
481 /**
482 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to {@link #MAX_SERVER_PRECISION}
483 *
484 * @return a clone of this lat LatLon
485 */
486 public LatLon getRoundedToOsmPrecision() {
487 return new LatLon(
488 roundToOsmPrecision(lat()),
489 roundToOsmPrecision(lon())
490 );
491 }
492
493 @Override
494 public int hashCode() {
495 return Objects.hash(x, y);
496 }
497
498 @Override
499 public boolean equals(Object obj) {
500 if (this == obj) return true;
501 if (obj == null || getClass() != obj.getClass()) return false;
502 LatLon that = (LatLon) obj;
503 return Double.compare(that.x, x) == 0 &&
504 Double.compare(that.y, y) == 0;
505 }
506
507 /**
508 * Converts this latitude/longitude to an instance of {@link ICoordinate}.
509 * @return a {@link ICoordinate} instance of this latitude/longitude
510 */
511 public ICoordinate toCoordinate() {
512 return new org.openstreetmap.gui.jmapviewer.Coordinate(lat(), lon());
513 }
514}
Note: See TracBrowser for help on using the repository browser.