2015-11-02 39 views
-1
func centerMapOnLocation(location: CLLocation) { 
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 
     regionRadius * 2.0, regionRadius * 2.0) 
    MapOutlet.setRegion(coordinateRegion, animated: true) 
} 

上面这个函数在我的视图控制器下面继续运行,虽然我从来没有编写任何循环,有人可以帮助发现不正确的逻辑。这里是视图控制器为什么这个函数保持循环?

import UIKit 
import MapKit 
import CoreLocation 


class ViewControllerPublic: UIViewController, CLLocationManagerDelegate { 
let locationManager = CLLocationManager() 



let initialLocation = CLLocation(latitude: 3.632488, longitude: -117.898886) 
override func viewDidLoad() { 
    super.viewDidLoad() 
    centerMapOnLocation(initialLocation) 

    // Ask for Authorisation from the User. 
    self.locationManager.requestAlwaysAuthorization() 

    // For use in foreground 
    self.locationManager.requestWhenInUseAuthorization() 

    if CLLocationManager.locationServicesEnabled() { 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
     locationManager.startUpdatingLocation() 
    } 

} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate 
    print("locations = \(locValue.latitude) \(locValue.longitude)") 
    let currentLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude) 
    centerMapOnLocation(currentLocation) 
} 

let regionRadius: CLLocationDistance = 2300 
func centerMapOnLocation(location: CLLocation) { 
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 
     regionRadius * 2.0, regionRadius * 2.0) 
    MapOutlet.setRegion(coordinateRegion, animated: true) 
} 

@IBOutlet weak var MapOutlet: MKMapView! 

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

}

+0

'didUpdateLocations'每个位置更新更新。并且您已经调用了该功能,这就是为什么它要求轻微的位置更改。 –

+0

你也可以公开一些允许用户控制'setUserTrackingMode:animated:'设置的UI,MapView将为你做所有事情 – Paulw11

回答

1

的你永远不会失效CLLocation manager从而@Ashish Kakkad说休息,只要你得到哪怕是一丁点的位置更改功能是越来越再次调用。如果您不想要这种行为,那么在didUpdateLocations中获得位置后,您需要执行locationManager.stopUpdatingLocation()。或者,如果您确实希望自己的应用在每次位置更改时更新地图,则可能需要考虑更改所需的位置准确性。