Search code examples
swiftmapkituserlocation

The centre locations in MapKit is not visible in the UiLabel


Unable to show the centrelocation of map in the label!

import UIKit import MapKit import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var myMapView: MKMapView!

@IBOutlet weak var addressLabel: UILabel!

let locationManager = CLLocationManager()
let regionInMeters: Double = 10000
var previousLocation: CLLocation?


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

    checkLocationServices()

}

func setupLocationManager() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
}

func centerViewOnUserLocation() {
    if let location = locationManager.location?.coordinate {
        let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        myMapView.setRegion(region, animated: true)
    }

}

// the Location service
func checkLocationServices() {
    if CLLocationManager.locationServicesEnabled() {
        setupLocationManager()
        checkLocationAuthorisation()

    } else {
        //show user to turn ON the services
    }
}

func checkLocationAuthorisation() {
    switch CLLocationManager.authorizationStatus() {
    case .authorizedWhenInUse:
        // do the stuff
        startTrackingLocation()

    case .denied:
        //Alert to turn ON the permissions
        break
    case .notDetermined:
        locationManager.requestWhenInUseAuthorization()
    case .restricted:
        // Alert to show what's up
        break
    case .authorizedAlways:

        break

    }
}

func startTrackingLocation() {
    myMapView.showsUserLocation = true
    centerViewOnUserLocation()
    locationManager.startUpdatingLocation()
    previousLocation = getCenterLocation(for: myMapView)
}

func getCenterLocation(for mapView: MKMapView) -> CLLocation {
    let latitude = mapView.centerCoordinate.latitude
    let longitude = mapView.centerCoordinate.longitude

    return CLLocation(latitude: latitude, longitude: longitude)
}


func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    // We'll be back
    checkLocationAuthorisation()
}

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {

    let center = getCenterLocation(for: myMapView)
    let geoCoder = CLGeocoder()

    guard let previousLocation = self.previousLocation else { return }

    guard center.distance(from: previousLocation) > 50 else { return }
    self.previousLocation = center

    geoCoder.reverseGeocodeLocation(center) { [weak self] (placemarks, error) in
        guard let self = self else { return }

        if let _ = error {
            //TODO: Show alert informing the user
            return
        }
        guard let placemark = placemarks?.first else {
            //TODO: Show alert informing the user
            return
        }

        let streetNumber = placemark.subThoroughfare  ?? ""
        let streetName = placemark.subThoroughfare ?? ""

        DispatchQueue.main.async {
            self.addressLabel.text = "\(streetNumber) \(streetName)"
        }
    }
}


@IBAction func satelliteView(_ sender: Any) {
    myMapView.mapType = MKMapType.satellite
}


@IBAction func hybridView(_ sender: Any) {
    myMapView.mapType = MKMapType.hybrid
}


@IBAction func standardView(_ sender: Any) {
    myMapView.mapType = MKMapType.standard
}


@IBAction func findDirections(_ sender: Any) {
}

}

enter image description here

The label in the app is supposed to show the centrelocation(pin) of the map. But don't know for where is it going wrong!


Solution

  • Changed the getCenterlocation function and its working fine! `func getCenterLocation(for mapView: MKMapView) -> CLLocation {

     let latitude=mapView.centerCoordinate.latitude
     let longitude=mapView.centerCoordinate.longitude
     return CLLocation(latitude:latitude, longitude:longitude)
    

    } func getCenterLocation(for myMapView: MKMapView) -> CLLocation {

     let latitude=myMapView.centerCoordinate.latitude
     let longitude=myMapView.centerCoordinate.longitude
     return CLLocation(latitude:latitude, longitude:longitude)
    

    }`