Swift MkMapView Map始终以当前位置为中心

时间:2016-12-05 17:35:29

标签: swift maps mkmapview

目前,我的代码会在用户的当前位置删除一个引脚。当我尝试移动地图时会出现一个小问题,因为视图将向后移动并以当前位置引脚为中心。我希望用户能够导航地图并移动它,如果用户切换视图控制器(转到另一个选项卡)并返回,则地图将以用户位置引脚为中心。我一直在尝试修改此代码来执行此操作,但我没有任何运气从哪里开始。

import UIKit
import MapKit
import CoreLocation
let newPin = MKPointAnnotation()

class MapVC: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {



@IBOutlet weak var map: MKMapView!

let locationManager =  CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    // User's location

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    if #available(iOS 8.0, *) {
        locationManager.requestAlwaysAuthorization()
    } else {
        // Fallback on earlier versions
    }
    locationManager.startUpdatingLocation()


    // add gesture recognizer
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(MapVC.mapLongPress(_:))) // colon needs to pass through info
    longPress.minimumPressDuration = 1.5 // in seconds
    //add gesture recognition
    map.addGestureRecognizer(longPress)
}

// func called when gesture recognizer detects a long press

func mapLongPress(_ recognizer: UIGestureRecognizer) {

    print("A long press has been detected.")

    let touchedAt = recognizer.location(in: self.map) // adds the location on the view it was pressed
    let touchedAtCoordinate : CLLocationCoordinate2D = map.convert(touchedAt, toCoordinateFrom: self.map) // will get coordinates

    let newPin = MKPointAnnotation()
    newPin.coordinate = touchedAtCoordinate
    map.addAnnotation(newPin)


}

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


    map.removeAnnotation(newPin)

    let location = locations.last! as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    //set region on the map
    map.setRegion(region, animated: true)

    newPin.coordinate = location.coordinate
    map.addAnnotation(newPin)





}

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


}

1 个答案:

答案 0 :(得分:1)

您可以使用自定义位置管理器类并使用选项调用didfinishlaunching中的单例函数,并在UserDefault中保存纬度和经度。在viewDidLoad中为mapView类设置摄像机位置

1.制作单身课程

var locationShareInstance:locationManagerClass = locationManagerClass()

class locationManagerClass: NSObject, CLLocationManagerDelegate, WebServiceDelegate , UIAlertViewDelegate
{
    var locationManager = CLLocationManager()
    class func sharedLocationManager() -> locationManagerClass
    {
        locationShareInstance = locationManagerClass()
        return locationShareInstance
    }

    func startStandardUpdates() {

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.activityType = .automotiveNavigation
        locationManager.distanceFilter = 10
        locationManager.pausesLocationUpdatesAutomatically = false

        if (Bundle.main.object(forInfoDictionaryKey: "NSLocationWhenInUseUsageDescription") != nil) {
            locationManager.requestWhenInUseAuthorization()
        }

        locationManager.startUpdatingLocation()

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // If it's a relatively recent event, turn off updates to save power.
        let location: CLLocation = locations.last!
        let strLocation = "\(location.coordinate.latitude)"
        if strLocation == "" {

        }else{
        UserDefaults.standard.set("\(location.coordinate.latitude)", forKey: "lat")
        UserDefaults.standard.set("\(location.coordinate.longitude)", forKey: "long")
        UserDefaults.standard.synchronize()
            debugPrint("Spedd: \(location.speed)")
//        self.updateLocationToServer()
            self.stopStandardUpdate()
        }
    }

    func stopStandardUpdate(){
        locationManager.stopUpdatingLocation()
    }


//MARK:- WHEN DENIED

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == CLAuthorizationStatus.denied {

        NSLog("DENIAL")

        UserDefaults.standard.set("\(0.0)", forKey: "lat")
        UserDefaults.standard.set("\(0.0)", forKey: "long")

        self.generateAlertToNotifyUser()
    }
}

func generateAlertToNotifyUser() {

    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined{

        var title: String
        title = ""
        let message: String = "Location Services are not able to determine your location"

        let alertView: UIAlertView = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Settings")
        alertView.show()
    }


    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.denied{

        var title: String

        title = "Location services are off"
        let message: String = "To post spots or find near by spots, you must turn on Location Services from Settings"

        let alertView: UIAlertView = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Settings")
        alertView.show()
    }

    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined
    {
        startStandardUpdates()
    }
}

}

在didfinishlaunchingwithoption中调用此函数

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

 let locationManager = locationManagerClass.sharedLocationManager()
        locationManager.startStandardUpdates()
}

3.在您班级的viewDidLoad中设置相机

 if UserDefaults.standard.object(forKey: "lat") != nil {
                let lat =  UserDefaults.standard.object(forKey: "lat") as! String
                let long = UserDefaults.standard.object(forKey: "long") as! String
                var userLoc = CLLocationCoordinate2D()
                userLoc.latitude = CDouble(lat)!
                userLoc.longitude = CDouble(long)!
                let span = MKCoordinateSpanMake(0.02, 0.02)
                let region = MKCoordinateRegion(center: userLoc, span: span)
                mapVw.setRegion(region, animated: true)
                mapVw.showsUserLocation = true

            }