0

I'm trying to display the users current location and calculate the distance he traveled and i'm getting error at displaying it on distance1.text, can somebody please help me. Thanks in advance and I'm very new to iOS app development, currently using swift3

import UIKit
import MapKit
import CoreLocation

class MapView1: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var distance1: UILabel!

    let locationManager = CLLocationManager()

    var startLocation:CLLocation!
    var lastLocation: CLLocation!
    var traveledDistance:Double = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true

        startLocation = nil
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK: Location Delegate Methods

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations.last

        let center1 = CLLocationCoordinate2D(latitude: location!.coordinate.latitude , longitude: location!.coordinate.longitude)

        let region1 = MKCoordinateRegion(center: center1, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

        self.mapView.setRegion(region1, animated: true)

        self.locationManager.stopUpdatingLocation()


        if startLocation == nil {
            startLocation = location
        }

        let distanceBetween: CLLocationDistance =
            location!.distance(from: startLocation)

        distance1.text = String(format: "%.2f", distanceBetween)
    }


    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error: " + error.localizedDescription)
    }

}
Bista
  • 7,869
  • 3
  • 27
  • 55

0 Answers0