MapKit缩放到用户当前位置

时间:2022-11-15 19:52:32

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 :

我试图简单地在地图上显示用户的位置,但是我需要在应用程序启动时,地图应该缩放到当前位置,但我不知道为什么地图根本不会缩放,它是这样的:

MapKit缩放到用户当前位置

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

6 个解决方案

#1


14  

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

我遇到了类似的问题,浪费了4天思考什么是错的。最后通过在viewDidLoad方法中创建这些代码行来解决:

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

In ViewDidLoad Method add these new changes code :

在ViewDidLoad方法中添加以下新更改代码:

override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        mapView.showsUserLocation = true
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self

         //Check for Location Services
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.requestWhenInUseAuthorization()
        }
        locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
        }
         //Zoom to user location
        let noLocation = CLLocationCoordinate2D()
        let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
        mapView.setRegion(viewRegion, animated: false)

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

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

希望这有助于解决您的问题。如果有任何进一步的问题,请随时发表评论。谢谢

#2


10  

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

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

Then, call in in viewDidLoad()

然后,在viewDidLoad()中调用

mapView.showsUserLocation = true
centerMapOnLocation(location: homeLocation)

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

这将启动应用程序,其中变量中指定的位置已放大。

#3


2  

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

#4


1  

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


0  

Try with MKMapViewDelegate func:

尝试使用MKMapViewDelegate func:

var isInitiallyZoomedToUserLocation: Bool = false 

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

#6


0  

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)

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

#1


14  

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

我遇到了类似的问题,浪费了4天思考什么是错的。最后通过在viewDidLoad方法中创建这些代码行来解决:

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

In ViewDidLoad Method add these new changes code :

在ViewDidLoad方法中添加以下新更改代码:

override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        mapView.showsUserLocation = true
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self

         //Check for Location Services
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.requestWhenInUseAuthorization()
        }
        locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
        }
         //Zoom to user location
        let noLocation = CLLocationCoordinate2D()
        let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
        mapView.setRegion(viewRegion, animated: false)

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

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

希望这有助于解决您的问题。如果有任何进一步的问题,请随时发表评论。谢谢

#2


10  

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

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

Then, call in in viewDidLoad()

然后,在viewDidLoad()中调用

mapView.showsUserLocation = true
centerMapOnLocation(location: homeLocation)

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

这将启动应用程序,其中变量中指定的位置已放大。

#3


2  

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

#4


1  

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


0  

Try with MKMapViewDelegate func:

尝试使用MKMapViewDelegate func:

var isInitiallyZoomedToUserLocation: Bool = false 

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

#6


0  

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)

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