用当前位置更新屏幕中心

时间:2016-10-06 19:51:45

标签: ios swift gps center region

我已经成功制作了一个应用程序,显示用户当前所在的蓝点。然而,截至目前,当用户移动时,屏幕的中心不跟随蓝点,因此如果用户移动蓝点,则只是退出屏幕并且用户必须滚动以跟上它。那不是用户友好的!我有以下代码:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!

    let locationManager = CLLocationManager()
    var mapp = MKMapView.self

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if (CLLocationManager.locationServicesEnabled())
        {
            self.locationManager.delegate = self
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.locationManager.requestWhenInUseAuthorization()
            self.locationManager.startUpdatingLocation()
            self.map.showsUserLocation = true
        }
        else
        {
            print("Location services are not enabled")
        }
    }

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

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
        self.map.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()
    }
}

我唯一的想法是我可以摆脱“stopUpdatingLocation()部分,然后它会不断更新每个新位置的新中心区域,但是我不确定是否没有使用stopUpdatingLocation是不好的做法感谢您的所有建议!

1 个答案:

答案 0 :(得分:1)

使用userTrackningMode会导致地图视图将地图置于该位置的中心,并开始跟踪用户的位置。如果地图缩小,地图视图会自动放大用户的位置,有效地更改当前可见区域。

使用它

mapView.setUserTrackingMode(.follow, animated:true)