gpt4 book ai didi

ios - MapKit 缩放到用户当前位置

转载 作者:IT王子 更新时间:2023-10-29 05:12:55 27 4
gpt4 key购买 nike

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

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

最佳答案

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

}

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

关于ios - MapKit 缩放到用户当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189147/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com