I have a tab bar, one is used to display the map. When I switch to this tab bar, it will request permission and get the current location automatically.
I finished the code, set the simulated location to Apple, it will show a blue dot in the center of the screen, but when I chose the custom location, specify a location, the blue dot is not displayed in the center of the map.
I need to drag the map, and will find the blue dot near the center location about 1~2km. I tested on the real device and have the same problem.
use the method to show the current location auto, but not show the blue dot.
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager!.delegate = self
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{
locationManager!.startUpdatingLocation()
locationManager!.desiredAccuracy = kCLLocationAccuracyBestForNavigation
}else{
locationManager!.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 100, 100)
mapView.setRegion(mapView.regionThatFits(coordinateRegion), animated: true)
location = newLocation
locationManager?.stopUpdatingLocation()
locationManager = nil
}
I added a button - when it not show the blue dot, clicking the button will set the blue dot in the center of the map. The two methods have the same function, but they produce different views. Why?
@IBAction func showUser() {
let region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 100, 100)
mapView.setRegion(mapView.regionThatFits(region), animated: true)
}
Screenshot
I just use this coding to update to location with center of mapview
Please add this keys into info.plist file
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>NSLocationAlwaysUsageDescription</key>
<string></string>
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
map.delegate = self
map.showsUserLocation = true
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{
locationManager.startUpdatingLocation()
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
}else{
locationManager.requestWhenInUseAuthorization()
}
}
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
mapView .setCenter(userLocation.coordinate, animated: true)
}
You can download demo from HERE