简体   繁体   中英

How to Center a Map on User Location IOS 9 SWIFT

Hi I have the below code which is finding the user location the radius within 1 mile:

let initialLocation = CLLocation(latitude: 51.5001524, longitude: -0.1262362)
let regionRadius: CLLocationDistance = 1000
var locationManager: CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()

    func centerMapOnLocation(location:CLLocation) {
        let coordianteRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
            regionRadius * 2.0, regionRadius * 2.0)
        mapView.setRegion(coordianteRegion, animated: true)
    }
    // Do any additional setup after loading the view, typically from a nib.
      centerMapOnLocation(initialLocation)

        }

This is perfect as gets a decent radius for user location, however i want to know, how do you center map on user location? 

i have tried a lot of methods but i do not seem to be able to get the map to center on user location.

Any help would be much appreciated!

Thanks

MKMapView使用userTrackingMode属性有一个内置的解决方案。

mapView.userTrackingMode = .Follow

I think this might help you

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    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))

    self.map.setRegion(region, animated: true)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM