001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.coor.conversion;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.text.DecimalFormat;
007
008import org.openstreetmap.josm.data.coor.ILatLon;
009import org.openstreetmap.josm.spi.preferences.Config;
010
011/**
012 * Coordinate format that converts a coordinate to degrees, minutes and seconds.
013 * @since 12735
014 */
015public class DMSCoordinateFormat extends AbstractCoordinateFormat {
016
017    private static final DecimalFormat DMS_MINUTE_FORMATTER = new DecimalFormat("00");
018    private static final DecimalFormat DMS_SECOND_FORMATTER = new DecimalFormat(
019            Config.getPref() == null ? "00.0" : Config.getPref().get("latlon.dms.decimal-format", "00.0"));
020    private static final String DMS60 = DMS_SECOND_FORMATTER.format(60.0);
021    private static final String DMS00 = DMS_SECOND_FORMATTER.format(0.0);
022
023    /**
024     * The unique instance.
025     */
026    public static final DMSCoordinateFormat INSTANCE = new DMSCoordinateFormat();
027
028    protected DMSCoordinateFormat() {
029        super("DEGREES_MINUTES_SECONDS", tr("deg\u00B0 min'' sec\""));
030    }
031
032    @Override
033    public String latToString(ILatLon ll) {
034        return degreesMinutesSeconds(ll.lat()) + ((ll.lat() < 0) ? SOUTH : NORTH);
035    }
036
037    @Override
038    public String lonToString(ILatLon ll) {
039       return degreesMinutesSeconds(ll.lon()) + ((ll.lon() < 0) ? WEST : EAST);
040    }
041
042    /**
043     * Replies the coordinate in degrees/minutes/seconds format
044     * @param pCoordinate The coordinate to convert
045     * @return The coordinate in degrees/minutes/seconds format
046     * @since 12561
047     */
048    public static String degreesMinutesSeconds(double pCoordinate) {
049
050        double tAbsCoord = Math.abs(pCoordinate);
051        int tDegree = (int) tAbsCoord;
052        double tTmpMinutes = (tAbsCoord - tDegree) * 60;
053        int tMinutes = (int) tTmpMinutes;
054        double tSeconds = (tTmpMinutes - tMinutes) * 60;
055
056        String sDegrees = Integer.toString(tDegree);
057        String sMinutes = DMS_MINUTE_FORMATTER.format(tMinutes);
058        String sSeconds = DMS_SECOND_FORMATTER.format(tSeconds);
059
060        if (DMS60.equals(sSeconds)) {
061            sSeconds = DMS00;
062            sMinutes = DMS_MINUTE_FORMATTER.format(tMinutes+1L);
063        }
064        if ("60".equals(sMinutes)) {
065            sMinutes = "00";
066            sDegrees = Integer.toString(tDegree+1);
067        }
068
069        return sDegrees + '\u00B0' + sMinutes + '\'' + sSeconds + '\"';
070    }
071
072}