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

Last change on this file since 9983 was 9983, checked in by Don-vip, 8 years ago

remove unused code

  • 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.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
51 /**
52 * The (0,0) coordinates.
53 * @since 6178
54 */
55 public static final LatLon ZERO = new LatLon(0, 0);
56
57 /**
58 * North and south pole.
59 */
60 public static final LatLon NORTH_POLE = new LatLon(90, 0);
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 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+1);
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 /**
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 R = 6378135;
328 double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
329 double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
330 double d = 2 * R * 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 * R;
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 LatLon#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 * Returns the value rounded to OSM precision. This function is now the same as
471 * {@link #roundToOsmPrecision(double)}, since the rounding error has been fixed.
472 * @param value lat/lon value
473 *
474 * @return rounded value
475 * @deprecated Use {@link #roundToOsmPrecision(double)} instead
476 */
477 @Deprecated
478 public static double roundToOsmPrecisionStrict(double value) {
479 return roundToOsmPrecision(value);
480 }
481
482 /**
483 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
484 * MAX_SERVER_PRECISION
485 *
486 * @return a clone of this lat LatLon
487 */
488 public LatLon getRoundedToOsmPrecision() {
489 return new LatLon(
490 roundToOsmPrecision(lat()),
491 roundToOsmPrecision(lon())
492 );
493 }
494
495 /**
496 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
497 * MAX_SERVER_PRECISION
498 *
499 * @return a clone of this lat LatLon
500 * @deprecated Use {@link #getRoundedToOsmPrecision()} instead
501 */
502 @Deprecated
503 public LatLon getRoundedToOsmPrecisionStrict() {
504 return getRoundedToOsmPrecision();
505 }
506
507 @Override
508 public int hashCode() {
509 return Objects.hash(x, y);
510 }
511
512 @Override
513 public boolean equals(Object obj) {
514 if (this == obj) return true;
515 if (!(obj instanceof LatLon)) return false;
516 LatLon that = (LatLon) obj;
517 return Double.compare(that.x, x) == 0 &&
518 Double.compare(that.y, y) == 0;
519 }
520
521 /**
522 * Converts this latitude/longitude to an instance of {@link ICoordinate}.
523 * @return a {@link ICoordinate} instance of this latitude/longitude
524 */
525 public ICoordinate toCoordinate() {
526 return new org.openstreetmap.gui.jmapviewer.Coordinate(lat(), lon());
527 }
528}
Note: See TracBrowser for help on using the repository browser.