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

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

Rework console output:

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