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

Last change on this file since 5268 was 5268, checked in by simon04, 12 years ago

fix #7740 - Fix roundToOsmPrecision() accuracy (patch by mrwojo)

  • Property svn:eol-style set to native
File size: 11.0 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.text.DecimalFormat;
14import java.text.NumberFormat;
15import java.util.Locale;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.Bounds;
19
20/**
21 * LatLon are unprojected latitude / longitude coordinates.
22 *
23 * This class is immutable.
24 *
25 * @author Imi
26 */
27public class LatLon extends Coordinate {
28
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 /**
50 * Replies true if lat is in the range [-90,90]
51 *
52 * @param lat the latitude
53 * @return true if lat is in the range [-90,90]
54 */
55 public static boolean isValidLat(double lat) {
56 return lat >= -90d && lat <= 90d;
57 }
58
59 /**
60 * Replies true if lon is in the range [-180,180]
61 *
62 * @param lon the longitude
63 * @return true if lon is in the range [-180,180]
64 */
65 public static boolean isValidLon(double lon) {
66 return lon >= -180d && lon <= 180d;
67 }
68
69 /**
70 * Replies true if lat is in the range [-90,90] and lon is in the range [-180,180]
71 *
72 * @return true if lat is in the range [-90,90] and lon is in the range [-180,180]
73 */
74 public boolean isValid() {
75 return isValidLat(lat()) && isValidLon(lon());
76 }
77
78 public static double toIntervalLat(double value) {
79 if (value < -90)
80 return -90;
81 if (value > 90)
82 return 90;
83 return value;
84 }
85
86 /**
87 * Returns a valid OSM longitude [-180,+180] for the given extended longitude value.
88 * For example, a value of -181 will return +179, a value of +181 will return -179.
89 * @param lon A longitude value not restricted to the [-180,+180] range.
90 */
91 public static double toIntervalLon(double value) {
92 if (isValidLon(value))
93 return value;
94 else {
95 int n = (int) (value + Math.signum(value)*180.0) / 360;
96 return value - n*360.0;
97 }
98 }
99
100 /**
101 * Replies the coordinate in degrees/minutes/seconds format
102 */
103 public static String dms(double pCoordinate) {
104
105 double tAbsCoord = Math.abs(pCoordinate);
106 int tDegree = (int) tAbsCoord;
107 double tTmpMinutes = (tAbsCoord - tDegree) * 60;
108 int tMinutes = (int) tTmpMinutes;
109 double tSeconds = (tTmpMinutes - tMinutes) * 60;
110
111 return tDegree + "\u00B0" + cDmsMinuteFormatter.format(tMinutes) + "\'"
112 + cDmsSecondFormatter.format(tSeconds) + "\"";
113 }
114
115 public static String dm(double pCoordinate) {
116
117 double tAbsCoord = Math.abs(pCoordinate);
118 int tDegree = (int) tAbsCoord;
119 double tMinutes = (tAbsCoord - tDegree) * 60;
120 return tDegree + "\u00B0" + cDmMinuteFormatter.format(tMinutes) + "\'";
121 }
122
123 public LatLon(double lat, double lon) {
124 super(lon, lat);
125 }
126
127 public LatLon(LatLon coor) {
128 super(coor.lon(), coor.lat());
129 }
130
131 public double lat() {
132 return y;
133 }
134
135 public final static String SOUTH = trc("compass", "S");
136 public final static String NORTH = trc("compass", "N");
137 public String latToString(CoordinateFormat d) {
138 switch(d) {
139 case DECIMAL_DEGREES: return cDdFormatter.format(y);
140 case DEGREES_MINUTES_SECONDS: return dms(y) + ((y < 0) ? SOUTH : NORTH);
141 case NAUTICAL: return dm(y) + ((y < 0) ? SOUTH : NORTH);
142 case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).north());
143 default: return "ERR";
144 }
145 }
146
147 public double lon() {
148 return x;
149 }
150
151 public final static String WEST = trc("compass", "W");
152 public final static String EAST = trc("compass", "E");
153 public String lonToString(CoordinateFormat d) {
154 switch(d) {
155 case DECIMAL_DEGREES: return cDdFormatter.format(x);
156 case DEGREES_MINUTES_SECONDS: return dms(x) + ((x < 0) ? WEST : EAST);
157 case NAUTICAL: return dm(x) + ((x < 0) ? WEST : EAST);
158 case EAST_NORTH: return cDdFormatter.format(Main.getProjection().latlon2eastNorth(this).east());
159 default: return "ERR";
160 }
161 }
162
163 /**
164 * @return <code>true</code> if the other point has almost the same lat/lon
165 * values, only differing by no more than
166 * 1 / {@link #MAX_SERVER_PRECISION MAX_SERVER_PRECISION}.
167 */
168 public boolean equalsEpsilon(LatLon other) {
169 double p = MAX_SERVER_PRECISION / 2;
170 return Math.abs(lat()-other.lat()) <= p && Math.abs(lon()-other.lon()) <= p;
171 }
172
173 /**
174 * @return <code>true</code>, if the coordinate is outside the world, compared
175 * by using lat/lon.
176 */
177 public boolean isOutSideWorld() {
178 Bounds b = Main.getProjection().getWorldBoundsLatLon();
179 return lat() < b.getMin().lat() || lat() > b.getMax().lat() ||
180 lon() < b.getMin().lon() || lon() > b.getMax().lon();
181 }
182
183 /**
184 * @return <code>true</code> if this is within the given bounding box.
185 */
186 public boolean isWithin(Bounds b) {
187 return b.contains(this);
188 }
189
190 /**
191 * Computes the distance between this lat/lon and another point on the earth.
192 * Uses Haversine formular.
193 * @param other the other point.
194 * @return distance in metres.
195 */
196 public double greatCircleDistance(LatLon other) {
197 double R = 6378135;
198 double sinHalfLat = sin(toRadians(other.lat() - this.lat()) / 2);
199 double sinHalfLon = sin(toRadians(other.lon() - this.lon()) / 2);
200 double d = 2 * R * asin(
201 sqrt(sinHalfLat*sinHalfLat +
202 cos(toRadians(this.lat()))*cos(toRadians(other.lat()))*sinHalfLon*sinHalfLon));
203 // For points opposite to each other on the sphere,
204 // rounding errors could make the argument of asin greater than 1
205 // (This should almost never happen.)
206 if (java.lang.Double.isNaN(d)) {
207 System.err.println("Error: NaN in greatCircleDistance");
208 d = PI * R;
209 }
210 return d;
211 }
212
213 /**
214 * Returns the heading, in radians, that you have to use to get from
215 * this lat/lon to another.
216 *
217 * (I don't know the original source of this formula, but see
218 * http://math.stackexchange.com/questions/720/how-to-calculate-a-heading-on-the-earths-surface
219 * for some hints how it is derived.)
220 *
221 * @param other the "destination" position
222 * @return heading in the range 0 <= hd < 2*PI
223 */
224 public double heading(LatLon other) {
225 double hd = atan2(sin(toRadians(this.lon() - other.lon())) * cos(toRadians(other.lat())),
226 cos(toRadians(this.lat())) * sin(toRadians(other.lat())) -
227 sin(toRadians(this.lat())) * cos(toRadians(other.lat())) * cos(toRadians(this.lon() - other.lon())));
228 hd %= 2 * PI;
229 if (hd < 0) {
230 hd += 2 * PI;
231 }
232 return hd;
233 }
234
235 /**
236 * Returns this lat/lon pair in human-readable format.
237 *
238 * @return String in the format "lat=1.23456 deg, lon=2.34567 deg"
239 */
240 public String toDisplayString() {
241 NumberFormat nf = NumberFormat.getInstance();
242 nf.setMaximumFractionDigits(5);
243 return "lat=" + nf.format(lat()) + "\u00B0, lon=" + nf.format(lon()) + "\u00B0";
244 }
245
246 public LatLon interpolate(LatLon ll2, double proportion) {
247 return new LatLon(this.lat() + proportion * (ll2.lat() - this.lat()),
248 this.lon() + proportion * (ll2.lon() - this.lon()));
249 }
250
251 public LatLon getCenter(LatLon ll2) {
252 return new LatLon((this.lat() + ll2.lat())/2.0, (this.lon() + ll2.lon())/2.0);
253 }
254
255 @Override public String toString() {
256 return "LatLon[lat="+lat()+",lon="+lon()+"]";
257 }
258
259 /**
260 * Returns the value rounded to OSM precisions, i.e. to
261 * LatLon.MAX_SERVER_PRECISION
262 *
263 * @return rounded value
264 */
265 public static double roundToOsmPrecision(double value) {
266 return Math.round(value * MAX_SERVER_INV_PRECISION) / MAX_SERVER_INV_PRECISION;
267 }
268
269 /**
270 * Returns the value rounded to OSM precision. This function is now the same as
271 * {@link #roundToOsmPrecision(double)}, since the rounding error has been fixed.
272 *
273 * @return rounded value
274 */
275 public static double roundToOsmPrecisionStrict(double value) {
276 return roundToOsmPrecision(value);
277 }
278
279 /**
280 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
281 * MAX_SERVER_PRECISION
282 *
283 * @return a clone of this lat LatLon
284 */
285 public LatLon getRoundedToOsmPrecision() {
286 return new LatLon(
287 roundToOsmPrecision(lat()),
288 roundToOsmPrecision(lon())
289 );
290 }
291
292 /**
293 * Replies a clone of this lat LatLon, rounded to OSM precisions, i.e. to
294 * MAX_SERVER_PRECISION
295 *
296 * @return a clone of this lat LatLon
297 */
298 public LatLon getRoundedToOsmPrecisionStrict() {
299 return new LatLon(
300 roundToOsmPrecisionStrict(lat()),
301 roundToOsmPrecisionStrict(lon())
302 );
303 }
304
305 @Override
306 public int hashCode() {
307 final int prime = 31;
308 int result = super.hashCode();
309 long temp;
310 temp = java.lang.Double.doubleToLongBits(x);
311 result = prime * result + (int) (temp ^ (temp >>> 32));
312 temp = java.lang.Double.doubleToLongBits(y);
313 result = prime * result + (int) (temp ^ (temp >>> 32));
314 return result;
315 }
316
317 @Override
318 public boolean equals(Object obj) {
319 if (this == obj)
320 return true;
321 if (!super.equals(obj))
322 return false;
323 if (getClass() != obj.getClass())
324 return false;
325 Coordinate other = (Coordinate) obj;
326 if (java.lang.Double.doubleToLongBits(x) != java.lang.Double.doubleToLongBits(other.x))
327 return false;
328 if (java.lang.Double.doubleToLongBits(y) != java.lang.Double.doubleToLongBits(other.y))
329 return false;
330 return true;
331 }
332}
Note: See TracBrowser for help on using the repository browser.