Convert MapKit latitude and longitude to DMS format

后端 未结 4 815
清歌不尽
清歌不尽 2021-02-02 04:35

I am able to determine the latitude and longitude of a location in the center of a map with the following:

func TargetGridReference(outletMapView_PrimaryTargetLo         


        
相关标签:
4条回答
  • 2021-02-02 04:46

    The first part of the accepted answer has a slight typo:

    let latDegrees = abs(Int(lat))

    will always produce positive latDegrees and therefore the return portion latDegrees >= 0 ? "N" : "S" will always produce N regardless of the input lat: Double sign.

    Just need change to lat >= 0 ? "N" : "S") as well as lon >= 0 ? "E" : "W") to evaluate the input values` sign directly.

    0 讨论(0)
  • 2021-02-02 04:49

    I made some updates to this code to get it to work in Swift3 (mostly using .truncatingRemainder(dividingBy: ) rather than %) and also expanded it to output DMM as well, and included functions for converting DMM and DMS to DD!

    extension CLLocationCoordinate2D {
    
        var latitudeMinutes:  Double { return (latitude * 3600).truncatingRemainder(dividingBy: 3600) / 60 }
        var latitudeSeconds:  Double { return ((latitude * 3600).truncatingRemainder(dividingBy: 3600)).truncatingRemainder(dividingBy: 60) }
    
        var longitudeMinutes: Double { return (longitude * 3600).truncatingRemainder(dividingBy: 3600) / 60 }
        var longitudeSeconds: Double { return ((longitude * 3600).truncatingRemainder(dividingBy: 3600)).truncatingRemainder(dividingBy: 60) }
    
        var dms:(latitude: String, longitude: String) {
    
            return (String(format:"%d°%d'%.1f\"%@",
                           Int(abs(latitude)),
                           Int(abs(latitudeMinutes)),
                           abs(latitudeSeconds),
                           latitude >= 0 ? "N" : "S"),
                    String(format:"%d°%d'%.1f\"%@",
                           Int(abs(longitude)),
                           Int(abs(longitudeMinutes)),
                           abs(longitudeSeconds),
                           longitude >= 0 ? "E" : "W"))
        }
    
        var dmm: (latitude: String, longitude: String) {
            return (String(format:"%d°%.4f'%@",
                          Int(abs(latitude)),
                          abs(latitudeMinutes),
                          latitude >= 0 ? "N" : "S"),
                   String(format:"%d°%.4f'%@",
                          Int(abs(longitude)),
                          abs(longitudeMinutes),
                          longitude >= 0 ? "E" : "W"))
        }
    }
    
    var coord = CLLocationCoordinate2D(latitude: 41.40338, longitude: 2.17403)
    
    coord.latitude // 41.40338
    coord.longitude // 2.17403
    coord.latitudeMinutes // 24.20280000000009
    coord.latitudeSeconds // 12.16800000000512
    coord.longitudeMinutes // 10.44180000000001
    coord.longitudeSeconds // 26.50800000000072
    
    coord.dms.latitude   // "41°24'12.2"N"
    coord.dms.longitude  // "2°10'26.5"E"
    coord.dmm.latitude   // "41°24.2028'N"
    coord.dmm.longitude  // "2°10.4418'E"
    

    These conversion functions also allow an input without indicating cardinal direction, but rather just supplying positive or negative:

    func DMStoDD(latDeg: Double, latMin: Double, latSec: Double, latDir: String?, longDeg: Double, longMin: Double, longSec: Double, longDir: String?) -> CLLocationCoordinate2D {
        var latitude = CLLocationDegrees()
        if latDeg > 0 {
            latitude = CLLocationDegrees(latDeg + ((latMin*60)/3600) + (latSec/3600))
            if latDir == "S" {latitude *= -1}
        }
        else{
            latitude = CLLocationDegrees((latDeg * -1) + ((latMin*60)/3600) + (latSec/3600))
            latitude *= -1
        }
    
        var longitude = CLLocationDegrees()
        if longDeg > 0 {
            longitude = CLLocationDegrees(longDeg + ((longMin*60)/3600) + (longSec/3600))
            if longDir == "W" {longitude *= -1}
        }
        else{
            longitude = CLLocationDegrees((longDeg * -1) + ((longMin*60)/3600) + (longSec/3600))
            longitude *= -1
        }
        return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
    
    coord = DMStoDD(latDeg: 41, latMin: 24, latSec: 12.2, latDir: "", longDeg: 2, longMin: 10, longSec: 26.5, longDir: "")
    coord.latitude // 41.40338888888889
    coord.longitude // 2.174027777777777
    

    And DMM to DD

    func DMMtoDD(latDeg: Double, latMin: Double, latDir: String?, longDeg: Double, longMin: Double, longDir: String?) -> CLLocationCoordinate2D {
        var latitude = CLLocationDegrees()
        if latDeg > 0 {
            latitude = CLLocationDegrees(latDeg + ((latMin*60)/3600))
            if latDir == "S" {latitude *= -1}
        }
        else{
            latitude = CLLocationDegrees((latDeg * -1) + ((latMin*60)/3600))
            latitude *= -1
        }
        var longitude = CLLocationDegrees()
        if longDeg > 0 {
            longitude = CLLocationDegrees(longDeg + ((longMin*60)/3600))
            if longDir == "W" {longitude *= -1}
        }
        else{
            longitude = CLLocationDegrees((longDeg * -1) + ((longMin*60)/3600))
            longitude *= -1
        }
        return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
    
    coord = DMMtoDD(latDeg: 41, latMin: 24.2028, latDir: "N", longDeg: 2, longMin: 10.4418, longDir: "E")
    coord.latitude // 41.40338
    coord.longitude // 41.40338
    
    0 讨论(0)
  • 2021-02-02 04:56

    Unfortunately there is no automatic conversion but you can easily create one as follow:

    Swift 4 or later

    func coordinateToDMS(latitude: Double, longitude: Double) -> (latitude: String, longitude: String) {
        let latDegrees = abs(Int(latitude))
        let latMinutes = abs(Int((latitude * 3600).truncatingRemainder(dividingBy: 3600) / 60))
        let latSeconds = Double(abs((latitude * 3600).truncatingRemainder(dividingBy: 3600).truncatingRemainder(dividingBy: 60)))
    
        let lonDegrees = abs(Int(longitude))
        let lonMinutes = abs(Int((longitude * 3600).truncatingRemainder(dividingBy: 3600) / 60))
        let lonSeconds = Double(abs((longitude * 3600).truncatingRemainder(dividingBy: 3600).truncatingRemainder(dividingBy: 60) ))
    
        return (String(format:"%d° %d' %.4f\" %@", latDegrees, latMinutes, latSeconds, latitude >= 0 ? "N" : "S"),
                String(format:"%d° %d' %.4f\" %@", lonDegrees, lonMinutes, lonSeconds, longitude >= 0 ? "E" : "W"))
    }
    

    let dms = coordinateToDMS(latitude: 48.8582487759147, longitude: 2.2945180844931)
    
    print(dms.latitude)  // "48° 51' 29.6956" N"
    print(dms.longitude) // "2° 17' 40.2651" E"
    

    You can also extend CLLocationCoordinate2D to get your latitude/longitude DMS description:

    import MapKit
    extension FloatingPoint {
        var minutes:  Self {
            return (self*3600)
                .truncatingRemainder(dividingBy: 3600)/60
        }
        var seconds:  Self {
            return (self*3600)
                .truncatingRemainder(dividingBy: 3600)
                .truncatingRemainder(dividingBy: 60)
        }
    }
    extension CLLocationCoordinate2D {
        var dms: (latitude: String, longitude: String) {
            return (String(format:"%d° %d' %.4f\" %@",
                           Int(abs(latitude)),
                           Int(abs(latitude.minutes)),
                           abs(latitude.seconds),
                           latitude >= 0 ? "N" : "S"),
                    String(format:"%d° %d' %.4f\" %@",
                           Int(abs(longitude)),
                           Int(abs(longitude.minutes)),
                           abs(longitude.seconds),
                           longitude >= 0 ? "E" : "W"))
        }
    }
    

    let coord = CLLocationCoordinate2D(latitude: 48.8582487759147, longitude: 2.2945180844931)
    
    coord.dms.latitude   // "48° 51' 29.6956" N"
    coord.dms.longitude  // "2° 17' 40.2651" E"
    
    0 讨论(0)
  • 2021-02-02 04:57

    accepted answer sometimes return invalid values, coordinateToDMS(latitude: 12.99999999, longitude: 0.0) returns latitude 12° 59' 60.0000" N

    enum GeoFormat {
        case D
        case DM
        case DMS
    }
    func dms(value: Double, format: GeoFormat)->String {
        let sign = value < 0.0 ? -1 : 1
        let value = abs(value)
        switch format {
        case .D:
            return String(format: "%+15.10f°", value * Double(sign))
        case .DM:
            var deg = Int(value)
            var min = round((value - Double(deg)) * 60 * 10000000) * 0.0000001
            if min < 60.0 {} else {
                min -= 60.0
                deg += 1
            }
            return String(format: "%+4d°%010.7f′", deg * sign, min)
        case .DMS:
            var deg = Int(value)
            let _min = (value - Double(deg)) * 60
            var min = Int(_min)
            var sec = round((_min - Double(min)) * 60 * 10000) * 0.0001
            if sec < 60.0 {} else {
                sec -= 60.0
                min += 1
            }
            if min < 60 {} else {
                min -= 60
                deg += 1
            }
            return String(format: "%+4d°%02d′%07.4f″", deg * sign, min, sec)
        }
    }
    
    let value = -12.999999997222222
    print(dms(value: value, format: .D))
    print(dms(value: value, format: .DM))
    print(dms(value: value, format: .DMS))
    

    prints, as required

     -12.9999999972°
     -12°59.9999998′
     -13°00′00.0000″
    
    0 讨论(0)
提交回复
热议问题