当用户移动地图时,Swift打印地图中心

时间:2018-01-10 17:02:41

标签: ios swift mapkit

我想在iOS 11下使用Swift绘制地图。我想,当应用程序启动时,地图会以用户的位置为中心。

当我启动应用程序时,控制台的输出是:

locations = 0.0 0.0
locations = 49.8375375633452 3.45672192960001
locations = 0.0 0.0
locations = 49.8375375633452 3.45672192960001

当我用手指移动地图时会出现另一个问题,我想打印地图中心的坐标(如果可能的话,还会显示屏幕上显示的区域),但没有任何反应。

这是我完整的课程代码。

import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {



    var locationManager = CLLocationManager()
    func checkLocationAuthorizationStatus() {
        if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            mapView.showsUserLocation = true
        } else {
            locationManager.requestWhenInUseAuthorization()
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        checkLocationAuthorizationStatus()
    }


    @IBOutlet weak var mapView: MKMapView!


    var currentLocation = CLLocation()

    override func viewDidLoad() {
        super.viewDidLoad()

        //For use when the app is open
        locationManager.requestWhenInUseAuthorization()
        // If location services is enabled get the users location
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters // You can change the locaiton accuary here.
            locationManager.startUpdatingLocation()
        }

        mapView.delegate = self
        mapView.register(MyClassMarkerView.self,
                         forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
        centerMapOnLocation(location: self.currentLocation.coordinate)

    }

    let regionRadius: CLLocationDistance = 1000

    func centerMapOnLocation(location: CLLocationCoordinate2D) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location,
                                                                  regionRadius, regionRadius)
        print("locations = \(location.latitude) \(location.longitude)")
        mapView.setRegion(coordinateRegion, animated: true)
    }


    // Print out the location to the console
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            self.currentLocation = location            
            print("locations = \(location.coordinate.latitude) \(location.coordinate.longitude)")
            locationManager.stopUpdatingLocation()
        }
    }


    // If we have been deined access give the user the option to change it
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if(status == CLAuthorizationStatus.denied) {
            showLocationDisabledPopUp()
        }
    }

    // Show the popup to the user if we have been deined access
    func showLocationDisabledPopUp() {
        let alertController = UIAlertController(title: "Background Location Access Disabled",
                                                message: "In order to deliver pizza we need your location",
                                                preferredStyle: .alert)

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)

        let openAction = UIAlertAction(title: "Open Settings", style: .default) { (action) in
            if let url = URL(string: UIApplicationOpenSettingsURLString) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
        alertController.addAction(openAction)

        self.present(alertController, animated: true, completion: nil)
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl) {
        let location = view.annotation as! myClass
        let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeWalking]
        location.mapItem().openInMaps(launchOptions: launchOptions)
    }

    func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        print ("Here we are")
        var center = mapView.centerCoordinate
        print ("Center is \(center)")
    }

}

我做错了什么?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您的ViewController也需要是Map View的delegate,因此将mapview连接为storyboard中的委托,并声明您的ViewController还要实现MKMapViewDelegate以接收您的事件期待。

此外,您使用的委托功能与MKMapViewDelegate中的委托功能不完全匹配,因此它不知道要调用哪个函数。你应该在Xcode中得到一个黄色警告。将其更改为:

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    print ("Here we are")
    var center = mapView.centerCoordinate
    print ("Center is \(center)")
}

答案 1 :(得分:0)

您的课程应声明如下

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
    ....
}