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条回答
▲ chillily
2楼-- · 2020-05-19 08:33

I faced similar issue and wasted 4 days thinking whats going wrong. Finally resolved with creating these lines of code in viewDidLoad Method :

    //Zoom to user location
    let noLocation = CLLocationCoordinate2D()
    let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
    mapView.setRegion(viewRegion, animated: false)
    mapView.showsUserLocation = true

In ViewDidLoad Method add these new changes code :

override func viewDidLoad() {

    super.viewDidLoad()

    let locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    // Check for Location Services
    if (CLLocationManager.locationServicesEnabled()) {
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
    }

    //Zoom to user location
    if let userLocation = locationManager.location?.coordinate {
        let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation, 200, 200)
        mapView.setRegion(viewRegion, animated: false)
    }

    self.locationManager = locationManager

    DispatchQueue.main.async {
        self.locationManager.startUpdatingLocation()
    }

}

Hope this helps to resolve your issue. Feel free to post comment if any further issue. Thanks

查看更多
甜甜的少女心
3楼-- · 2020-05-19 08:33

Code:

import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var mapview: MKMapView!

let locationmanager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    mapview.mapType = MKMapType.standard

    let location = CLLocationCoordinate2DMake(22.4651, 70.0771)

    let span = MKCoordinateSpanMake(0.5, 0.5)
    let region =  MKCoordinateRegionMake(location, span)
    mapview.setRegion(region, animated: true)

    let annonation = MKPointAnnotation()
    annonation.coordinate = location
    annonation.title = "Chandi Bazar"
    annonation.subtitle = "Jamnagar"
    //
    mapview.addAnnotation(annonation)

    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)")

    locationmanager.stopUpdatingLocation()
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
    if (annotation is MKUserLocation)
    {
        return nil
    }

    let annotationidentifier = "Annotationidentifier"

    var annotationview:MKAnnotationView
    annotationview = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationidentifier)

    let btn = UIButton(type: .detailDisclosure)

    btn.addTarget(self, action: #selector(ViewController.hirenagravat(sender:)), for: .touchUpInside)

    annotationview.rightCalloutAccessoryView = btn

    annotationview.image = UIImage(named: "images (4).jpeg")

    annotationview.canShowCallout = true

    return annotationview
}

func hirenagravat(sender:UIButton)
{
    let fvc = storyboard?.instantiateViewController(withIdentifier: "secondViewController") as? secondViewController
    self.navigationController?.pushViewController(fvc!, animated: true)
}
查看更多
登录 后发表回答