caipivara
10/2/2015 - 1:46 AM

Swift - Extension to CLLocation to get cartesian representation for a coordinate. source: http://stackoverflow.com/a/5983282/273119

Swift - Extension to CLLocation to get cartesian representation for a coordinate. source: http://stackoverflow.com/a/5983282/273119

import Darwin
import Foundation
import CoreLocation

extension CLLocation {
    
    /**
        source: http://stackoverflow.com/a/5983282/273119
    
        Find cartesian representation for latitude, longitude and altitude.
        returns (x,y,z)
    */
    var cartesianCoordinates: (Double, Double, Double) {
        let rE = 6378137.0
        let rP = 6356752.31424518
        
        let latrad = coordinate.latitude/180.0 * M_PI
        let lonrad = coordinate.longitude/180.0 * M_PI
        
        let coslat = cos(latrad)
        let sinlat = sin(latrad)
        let coslon = cos(lonrad)
        let sinlon = sin(lonrad)
        
        let term1 = (pow(rE, 2) * coslat) / sqrt(pow(rE, 2) * pow(coslat,2) + pow(rP,2) * pow(sinlat, 2))
        
        let term2 = altitude * coslat + term1
        
        let x = coslon * term2
        let y = sinlon * term2
        let z = altitude * sinlat + (pow(rP, 2) * sinlat) / sqrt(pow(rE, 2) * pow(coslat, 2) + pow(rP, 2) * pow(sinlat, 2))
        
        return (x,y,z)
    }
    
}