繁体   English   中英

MapKit 缩放到用户当前位置

[英]MapKit zoom to user current location

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

在此处输入图片说明

这是代码:

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

我遇到了类似的问题,浪费了 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()
    }

}

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

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

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

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

}

代码:

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

尝试使用 MKMapViewDelegate 函数:

var isInitiallyZoomedToUserLocation: Bool = false 

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

当您设置区域时 -> 您无法再缩放地图。 下面来解决这个问题

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
}

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.setRegion(region, animated: true)
    }

斯威夫特 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)

在此处输入图片说明

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM