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

Last change on this file since 6670 was 6566, checked in by simon04, 10 years ago

fix #9494 - Advanced object info: add "Center of bounding box", and for ways "Centroid"

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