MapKit увеличить текущее местоположение пользователя

Я пытаюсь просто показать местоположение пользователя на карте, но мне нужно, чтобы при запуске приложения карта масштабировалась до текущего местоположения, но я не знаю, почему карта вообще не масштабируется, и это выглядит так:

enter image description here

Вот код:

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

Ответ 1

Я столкнулся с подобной проблемой и потратил впустую 4 дня, думая, что идет не так. Окончательно решено с созданием этих строк кода в методе viewDidLoad:

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

В методе ViewDidLoad добавьте новый код изменений:

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()
    }

}

Надеюсь, это поможет решить вашу проблему. Не стесняйтесь оставлять комментарии, если возникнут какие-либо проблемы. Спасибо

Ответ 2

Вот еще один подход для Swift 3, XCode 8.2. Сначала запишите вспомогательную функцию:

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

Затем зайдите в viewDidLoad()

mapView.showsUserLocation = true
centerMapOnLocation(location: homeLocation)

Это запустит приложение с местоположением, указанным в переменной, увеличенной.

Ответ 3

В Swift 4.2 произошли изменения с этим кодом. Вот как это работает сейчас:

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()
    }

}

Ответ 4

код:

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

Ответ 5

когда вы устанавливаете область → , вы больше не можете масштабировать карту. ниже, чтобы исправить это.

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
}

Ответ 6

Попробуйте с помощью функции MKMapViewDelegate:

var isInitiallyZoomedToUserLocation: Bool = false 

func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    if !isInitiallyZoomedToUserLocation {
       isInitiallyZoomedToUserLocation = true
       mapView.showAnnotations([userLocation], animated: true)
    }
}

Ответ 7

Свифт 4.1. Чтобы изменить уровень масштабирования, необходимо изменить значение диапазона, т.е. 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(self.mapView, regionDidChangeAnimated: true)
}

Ответ 8

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