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

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

Java 7: use Objects.equals and Objects.hash

  • Property svn:eol-style set to native
File size: 15.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 private static DecimalFormat cDmsMinuteFormatter = new DecimalFormat("00");
59 private static DecimalFormat cDmsSecondFormatter = new DecimalFormat("00.0");
60 private static DecimalFormat cDmMinuteFormatter = new DecimalFormat("00.000");
61 public static final DecimalFormat cDdFormatter;
62 public static final DecimalFormat cDdHighPecisionFormatter;
63 static {
64 // Don't use the localized decimal separator. This way we can present
65 // a comma separated list of coordinates.
66 cDdFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
67 cDdFormatter.applyPattern("###0.0######");
68 cDdHighPecisionFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.UK);
69 cDdHighPecisionFormatter.applyPattern("###0.0##########");
70 }
71
72 private static final String cDms60 = cDmsSecondFormatter.format(60.0);
73 private static final String cDms00 = cDmsSecondFormatter.format(0.0);
74 private static final String cDm60 = cDmMinuteFormatter.format(60.0);
75 private static final String cDm00 = cDmMinuteFormatter.format(0.0);
76
77 /**
78 * Replies true if lat is in the range [-90,90]
79 *
80 * @param lat the latitude
81 * @return true if lat is in the range [-90,90]
82 */
83 public static boolean isValidLat(double lat) {
84 return lat >= -90d && lat <= 90d;
85 }
86
87 /**
88 * Replies true if lon is in the range [-180,180]
89 *
90 * @param lon the longitude
91 * @return true if lon is in the range [-180,180]
92 */
93 public static boolean isValidLon(double lon) {
94 return lon >= -180d && lon <= 180d;
95 }
96
97 /**
98 * Replies true if lat is in the range [-90,90] and lon is in the range [-180,180]
99 *
100 * @return true if lat is in the range [-90,90] and lon is in the range [-180,180]
101 */
102 public boolean isValid() {
103 return isValidLat(lat()) && isValidLon(lon());
104 }
105
106 public static double toIntervalLat(double value) {
107 if (value < -90)
108 return -90;
109 if (value > 90)
110 return 90;
111 return value;
112 }
113
114 /**
115 * Returns a valid OSM longitude [-180,+180] for the given extended longitude value.
116 * For example, a value of -181 will return +179, a value of +181 will return -179.
117 * @param value A longitude value not restricted to the [-180,+180] range.
118 * @return a valid OSM longitude [-180,+180]
119 */
120 public static double toIntervalLon(double value) {
121 if (isValidLon(value))
122 return value;
123 else {
124 int n = (int) (value + Math.signum(value)*180.0) / 360;
125 return value - n*360.0;
126 }
127 }
128
129 /**
130 * Replies the coordinate in degrees/minutes/seconds format
131 * @param pCoordinate The coordinate to convert
132 * @return The coordinate in degrees/minutes/seconds format
133 */
134 public static String dms(double pCoordinate) {
135
136 double tAbsCoord = Math.abs(pCoordinate);
137 int tDegree = (int) tAbsCoord;
138 double tTmpMinutes = (tAbsCoord - tDegree) * 60;
139 int tMinutes = (int) tTmpMinutes;
140 double tSeconds = (tTmpMinutes - tMinutes) * 60;
141
142 String sDegrees = Integer.toString(tDegree);
143 String sMinutes = cDmsMinuteFormatter.format(tMinutes);
144 String sSeconds = cDmsSecondFormatter.format(tSeconds);
145
146 if (cDms60.equals(sSeconds)) {
147 sSeconds = cDms00;
148 sMinutes = cDmsMinuteFormatter.format(tMinutes+1);
149 }
150 if ("60".equals(sMinutes)) {
151 sMinutes = "00";
152 sDegrees = Integer.toString(tDegree+1);
153 }
154
155 return sDegrees + '\u00B0' + sMinutes + '\'' + sSeconds + '\"';
156 }
157
158 /**
159 * Replies the coordinate in degrees/minutes format
160 * @param pCoordinate The coordinate to convert
161 * @return The coordinate in degrees/minutes format
162 */
163 public static String dm(double pCoordinate) {
164
165 double tAbsCoord = Math.abs(pCoordinate);
166 int tDegree = (int) tAbsCoord;
167 double tMinutes = (tAbsCoord - tDegree) * 60;
168
169 String sDegrees = Integer.toString(tDegree);
170 String sMinutes = cDmMinuteFormatter.format(tMinutes);
171
172 if (sMinutes.equals(cDm60)) {
173 sMinutes = cDm00;
174 sDegrees = Integer.toString(tDegree+1);
175 }
176
177 return sDegrees + '\u00B0' + sMinutes + '\'';
178 }
179
180 /**
181 * Constructs a new {@link LatLon}
182 * @param lat the latitude, i.e., the north-south position in degrees
183 * @param lon the longitude, i.e., the east-west position in degrees
184 */
185 public LatLon(double lat, double lon) {
186 super(lon, lat);
187 }
188
189 protected LatLon(LatLon coor) {
190 super(coor.lon(), coor.lat());
191 }
192
193 public LatLon(ICoordinate coor) {
194 this(coor.getLat(), coor.getLon());
195 }
196
197
198 /**
199 * Returns the latitude, i.e., the north-south position in degrees.
200 * @return the latitude
201 */
202 public double lat() {
203 return y;
204 }
205
206 public static final String SOUTH = trc("compass", "S");
207 public static final String NORTH = trc("compass", "N");
208
209 public String latToString(CoordinateFormat d) {
210 switch(d) {
211 case DECIMAL_DEGREES: return cDdFormatter.format(y);
212 case DEGREES_MINUTES_SECONDS: return dms(y) + ((y < 0) ? SOUTH : NORTH);
213 case NAUTICAL: return dm(y) + ((y < 0) ? SOUTH : NORTH);
214 case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).north());
215 default: return "ERR";
216 }
217 }
218
219 /**
220 * Returns the longitude, i.e., the east-west position in degrees.
221 * @return the longitude
222 */
223 public double lon() {
224 return x;
225 }
226
227 public static final String WEST = trc("compass", "W");
228 public static final String EAST = trc("compass", "E");
229
230 public String lonToString(CoordinateFormat d) {
231 switch(d) {
232 case DECIMAL_DEGREES: return cDdFormatter.format(x);
233 case DEGREES_MINUTES_SECONDS: return dms(x) + ((x < 0) ? WEST : EAST);
234 case NAUTICAL: return dm(x) + ((x < 0) ? WEST : EAST);
235 case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).east());
236 default: return "ERR";
237 }
238 }
239
240 /**
241 * @param other other lat/lon
242 * @return <code>true</code> if the other point has almost the same lat/lon
243 * values, only differing by no more than 1 / {@link #MAX_SERVER_PRECISION MAX_SERVER_PRECISION}.
244 */
245 public boolean equalsEpsilon(LatLon other) {
246 double p = MAX_SERVER_PRECISION / 2;
247 return Math.abs(lat()-other.lat()) <= p && Math.abs(lon()-other.lon()) <= p;
248 }
249
250 /**
251 * Determines if this lat/lon is outside of the world
252 * @return <code>true</code>, if the coordinate is outside the world, compared by using lat/lon.
253 */
254 public boolean isOutSideWorld() {
255 Bounds b = Main.getProjection().getWorldBoundsLatLon();
256 return lat() < b.getMinLat() || lat() > b.getMaxLat() ||
257 lon() < b.getMinLon() || lon() > b.getMaxLon();
258 }
259
260 /**
261 * Determines if this lat/lon is within the given bounding box.
262 * @param b bounding box
263 * @return <code>true</code> if this is within the given bounding box.
264 */
265 public boolean isWithin(Bounds b) {
266 return b.contains(this);
267 }
268
269 /**
270 * Check if this is contained in given area or area is null.
271 *
272 * @param a Area
273 * @return <code>true</code> if this is contained in given area or area is null.
274 */
275 public boolean isIn(Area a) {
276 return a == null || a.contains(x, y);
277 }
278
279 /**
280 * Computes the distance between this lat/lon and another point on the earth.
281 * Uses Haversine formular.
282 * @param other the other point.
283 * @return distance in metres.
284 */
285 public double greatCircleDistance(LatLon other) {
286 double R = 6378135;
287 double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
288 double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
289 double d = 2 * R * asin(
290 sqrt(sinHalfLat*sinHalfLat +
291 cos(toRadians(this.lat()))*cos(toRadians(other.lat()))*sinHalfLon*sinHalfLon));
292 // For points opposite to each other on the sphere,
293 // rounding errors could make the argument of asin greater than 1
294 // (This should almost never happen.)
295 if (java.lang.Double.isNaN(d)) {
296 Main.error("NaN in greatCircleDistance");
297 d = PI * R;
298 }
299 return d;
300 }
301
302 /**
303 * Returns the heading, in radians, that you have to use to get from this lat/lon to another.
304 *
305 * (I don't know the original source of this formula, but see
306 * <a href="https://math.stackexchange.com/questions/720/how-to-calculate-a-heading-on-the-earths-surface">this question</a>
307 * for some hints how it is derived.)
308 *
309 * @param other the "destination" position
310 * @return heading in the range 0 &lt;= hd &lt; 2*PI
311 */
312 public double heading(LatLon other) {
313 double hd = atan2(sin(toRadians(this.lon() - other.lon())) * cos(toRadians(other.lat())),
314 cos(toRadians(this.lat())) * sin(toRadians(other.lat())) -
315 sin(toRadians(this.lat())) * cos(toRadians(other.lat())) * cos(toRadians(this.lon() - other.lon())));
316 hd %= 2 * PI;
317 if (hd < 0) {
318 hd += 2 * PI;
319 }
320 return hd;
321 }
322
323 /**
324 * Returns this lat/lon pair in human-readable format.
325 *
326 * @return String in the format "lat=1.23456 deg, lon=2.34567 deg"
327 */
328 public String toDisplayString() {
329 NumberFormat nf = NumberFormat.getInstance();
330 nf.setMaximumFractionDigits(5);
331 return "lat=" + nf.format(lat()) + "\u00B0, lon=" + nf.format(lon()) + '\u00B0';
332 }
333
334 /**
335 * Returns this lat/lon pair in human-readable format separated by {@code separator}.
336 * @param separator values separator
337 * @return String in the format {@code "1.23456[separator]2.34567"}
338 */
339 public String toStringCSV(String separator) {
340 return Utils.join(separator, Arrays.asList(
341 latToString(CoordinateFormat.DECIMAL_DEGREES),
342 lonToString(CoordinateFormat.DECIMAL_DEGREES)
343 ));
344 }
345
346 public LatLon interpolate(LatLon ll2, double proportion) {
347 return new LatLon(this.lat() + proportion * (ll2.lat() - this.lat()),
348 this.lon() + proportion * (ll2.lon() - this.lon()));
349 }
350
351 public LatLon getCenter(LatLon ll2) {
352 return new LatLon((this.lat() + ll2.lat())/2.0, (this.lon() + ll2.lon())/2.0);
353 }
354
355 /**
356 * Returns the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
357 *
358 * @param ll the specified coordinate to be measured against this {@code LatLon}
359 * @return the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
360 * @since 6166
361 */
362 public double distance(final LatLon ll) {
363 return super.distance(ll);
364 }
365
366 /**
367 * Returns the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}.
368 *
369 * @param ll the specified coordinate to be measured against this {@code LatLon}
370 * @return the square of the euclidean distance from this {@code LatLon} to a specified {@code LatLon}
371 * @since 6166
372 */
373 public double distanceSq(final LatLon ll) {
374 return super.distanceSq(ll);
375 }
376
377 @Override
378 public String toString() {
379 return "LatLon[lat="+lat()+",lon="+lon()+']';
380 }
381
382 /**
383 * Returns the value rounded to OSM precisions, i.e. to {@link LatLon#MAX_SERVER_PRECISION}.
384 * @param value lat/lon value
385 *
386 * @return rounded value
387 */
388 public static double roundToOsmPrecision(double value) {
389 return Math.round(value * MAX_SERVER_INV_PRECISION) / MAX_SERVER_INV_PRECISION;
390 }
391
392 /**
393 * Returns the value rounded to OSM precision. This function is now the same as
394 * {@link #roundToOsmPrecision(double)}, since the rounding error has been fixed.
395 * @param value lat/lon value
396 *
397 * @return rounded value
398 */
399 public static double roundToOsmPrecisionStrict(double value) {
400 return roundToOsmPrecision(value);
401 }
402
403 /**
404 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
405 * MAX_SERVER_PRECISION
406 *
407 * @return a clone of this lat LatLon
408 */
409 public LatLon getRoundedToOsmPrecision() {
410 return new LatLon(
411 roundToOsmPrecision(lat()),
412 roundToOsmPrecision(lon())
413 );
414 }
415
416 /**
417 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
418 * MAX_SERVER_PRECISION
419 *
420 * @return a clone of this lat LatLon
421 */
422 public LatLon getRoundedToOsmPrecisionStrict() {
423 return new LatLon(
424 roundToOsmPrecisionStrict(lat()),
425 roundToOsmPrecisionStrict(lon())
426 );
427 }
428
429 @Override
430 public int hashCode() {
431 return Objects.hash(super.hashCode());
432 }
433
434 @Override
435 public boolean equals(Object obj) {
436 if (this == obj) return true;
437 if (obj == null || getClass() != obj.getClass()) return false;
438 return super.equals(obj);
439 }
440
441 public ICoordinate toCoordinate() {
442 return new org.openstreetmap.gui.jmapviewer.Coordinate(lat(), lon());
443 }
444}
Note: See TracBrowser for help on using the repository browser.