【问题标题】:Swift MkMapView Map is always centered around current locationSwift MkMapView 地图始终以当前位置为中心
【发布时间】:2016-12-05 17:35:29
【问题描述】:

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

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.
}


}

【问题讨论】:

    标签: swift maps mkmapview


    【解决方案1】:

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

    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
    
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 2011-09-04
      相关资源
      最近更新 更多