Show Current Location and Update Location in MKMapView in Swift

前端 未结 10 1453
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 12:06

I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (MKMapView). I want to find and up

相关标签:
10条回答
  • 2020-12-02 12:59

    For Swift 2, you should change it to the following:

    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.01, longitudeDelta: 0.01))
    
        self.map.setRegion(region, animated: true)
    }
    
    0 讨论(0)
  • 2020-12-02 13:02

    Hi Sometimes setting the showsUserLocation in code doesn't work for some weird reason.

    So try a combination of the following.

    In viewDidLoad()

      self.mapView.showsUserLocation = true
    

    Go to your storyboard in Xcode, on the right panel's attribute inspector tick the User location check box, like in the attached image. run your app and you should be able to see the User location

    0 讨论(0)
  • 2020-12-02 13:03

    In Swift 4, I had used the locationManager delegate function as defined above ..

    func locationManager(manager: CLLocationManager!, 
        didUpdateLocations locations: [AnyObject]!) {
    

    .. but this needed to be changed to ..

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

    This came from .. https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift - thanks!

    0 讨论(0)
  • 2020-12-02 13:04

    you have to override CLLocationManager.didUpdateLocations

     func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        let userLocation:CLLocation = locations[0] as CLLocation
        locationManager.stopUpdatingLocation()
    
        let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
    
        let span = MKCoordinateSpanMake(0.5, 0.5)
    
        let region = MKCoordinateRegion (center:  location,span: span)
    
        mapView.setRegion(region, animated: true)
    }
    

    you also have to add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription to your plist setting Result as value

    0 讨论(0)
提交回复
热议问题