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

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

fix #8987 - Fix NPE and Findbugs/Sonar violations

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