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

Last change on this file since 6162 was 6162, checked in by bastiK, 11 years ago

applied #8987 - immutable coordinates (patch by shinigami)

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