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

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

fix potential NPEs and Sonar issues related to serialization

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