2016年5月8日 星期日

iOS Swift GPS 定位

定位功能

1.Main.storyboard拉label

2.在Info.plist的 Information Property List點"+",
在左邊key輸入"NSLocationWhenInUseUsageDescription"
在右邊Value輸入"The application uses this information to show you your location"

3.ViewController.swift

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    
    
    @IBOutlet weak var lblLat: UILabel!
    @IBOutlet weak var lblLon: UILabel!
    @IBOutlet weak var lblHorizontal: UILabel!
    @IBOutlet weak var lblAltitude: UILabel!
    @IBOutlet weak var lblVertical: UILabel!
    @IBOutlet weak var lblDistance: UILabel!
    
    var locationManager: CLLocationManager = CLLocationManager()
    var startLocation: CLLocation!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        
        startLocation = CLLocation(latitude: 22.6657786, longitude: 120.3033831) //目標緯度經度
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //定位資訊
        let latestLocation: AnyObject = locations[locations.count - 1]
        
        lblLat.text = String(format: "%.4f", latestLocation.coordinate.latitude) //緯度
        lblLon.text = String(format: "%.4f", latestLocation.coordinate.longitude) //經度
        lblHorizontal.text = String(format: "%.4f", latestLocation.horizontalAccuracy) //水平精度
        lblAltitude.text = String(format: "%.4f", latestLocation.altitude) //海拔高度
        lblVertical.text = String(format: "%.4f", latestLocation.verticalAccuracy) //垂直精度
        
        let distanceBetween: CLLocationDistance =
            latestLocation.distanceFromLocation(startLocation) //計算startLocation與latestLocation距離
        
        lblDistance.text = String(format: "%.2f", distanceBetween) //距離 公尺
    }
    
    func locationManager(manager: CLLocationManager,
                         didFailWithError error: NSError) {
        
    }
    
}



3.參考連結:
http://www.techotopia.com/index.php/A_Swift_Example_iOS_8_Location_Application
http://stackoverflow.com/questions/29931302/initialize-a-cllocation-object-in-swift-with-latitude-and-longitude