MapKit zoom to user current location

2020-05-19 08:01发布

I am trying to simply show user's location on the map, but I need to when app launches, the map should zoom to current location ,but I don't know why map doesn't zoom at all and it's like this :

enter image description here

Here is the code :

class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        mapView.showsUserLocation = true
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self
        DispatchQueue.main.async {
            self.locationManager.startUpdatingLocation()
        }
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        let location = locations.last as! CLLocation
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        var region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
        region.center = mapView.userLocation.coordinate
        mapView.setRegion(region, animated: true)
    }

8条回答
Deceive 欺骗
2楼-- · 2020-05-19 08:10
func animateToUserLocation() {
    if let annoation = mapView.annotations.filter ({ $0 is MKUserLocation }).first {
        let coordinate = annoation.coordinate
        let viewRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 200, longitudinalMeters: 200)
        mapView.setRegion(viewRegion, animated: true)
    }
}
查看更多
姐就是有狂的资本
3楼-- · 2020-05-19 08:16

In swift 4.1. To change the Zoom level you need to change the span value i.e MKCoordinateSpan(latitudeDelta: 0.95, longitudeDelta: 0.95)

 let lat =  "33.847105"
    let long = "-118.2673272"
    let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: Double(lat)!, longitude: Double(long)!), span: MKCoordinateSpan(latitudeDelta: 0.95, longitudeDelta: 0.95))
    DispatchQueue.main.async {
        self.mapView.setRegion(region, animated: true)
    }

Swift 5.0

let span = MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta:
0.01)
let coordinate = CLLocationCoordinate2D.init(latitude: 21.282778, longitude: -157.829444) // provide you lat and long 
let region = MKCoordinateRegion.init(center: coordinate, span: span)
mapView.setRegion(region, animated: true)

enter image description here

查看更多
淡お忘
4楼-- · 2020-05-19 08:23

when you set region -> you cannot zoom the map anymore. below to fix that

func yourFuncName() {
//this is global var
regionHasBeenCentered = false
if !self.regionHasBeenCentered {
    let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
    let userLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(_cllocationOfUserCurrentLocation!.coordinate.latitude, _cllocationOfUserCurrentLocation!.coordinate.longitude)
    let region: MKCoordinateRegion = MKCoordinateRegionMake(userLocation, span)

    self.mapView.setRegion(region, animated: true)
    self.regionHasBeenCentered = true
    }

    self.mapView.showsUserLocation = true
}
查看更多
迷人小祖宗
5楼-- · 2020-05-19 08:28

Here's another approach for Swift 3, XCode 8.2. First, write out a helper function:

let homeLocation = CLLocation(latitude: 37.6213, longitude: -122.3790)
let regionRadius: CLLocationDistance = 200
func centerMapOnLocation(location: CLLocation)
{
    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
                                           regionRadius * 2.0, regionRadius * 2.0)
    mapView.setRegion(coordinateRegion, animated: true)
}

Then, call in in viewDidLoad()

mapView.showsUserLocation = true
centerMapOnLocation(location: homeLocation)

This will start the app with the location specified in the variable zoomed in.

查看更多
再贱就再见
6楼-- · 2020-05-19 08:28

Try with MKMapViewDelegate func:

var isInitiallyZoomedToUserLocation: Bool = false 

func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    if !isInitiallyZoomedToUserLocation {
       isInitiallyZoomedToUserLocation = true
       mapView.showAnnotations([userLocation], animated: true)
    }
}
查看更多
We Are One
7楼-- · 2020-05-19 08:30

In Swift 4.2 there has been changes with this code. Here is how it works now:

import UIKit
import MapKit
import CoreLocation

class MapVC: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    var locationManager = CLLocationManager()
    let authorizationStatus = CLLocationManager.authorizationStatus()
    let regionRadius: Double = 1000

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self
        locationManager.delegate = self
        configureLocationServices()
    }

    func centerMapOnUserLocation() {
        guard let coordinate = locationManager.location?.coordinate else {return}
        let coordinateRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
        mapView.setRegion(coordinateRegion, animated: true)
    }

    func configureLocationServices() {
        if authorizationStatus == .notDetermined {
            locationManager.requestAlwaysAuthorization()
        } else {
            return
        }
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        centerMapOnUserLocation()
    }

}
查看更多
登录 后发表回答