您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Swift中的MKMapView中显示当前位置并更新位置

在Swift中的MKMapView中显示当前位置并更新位置

您必须重写CLLocationManager.didUpdateLocations(CLLocationManagerDelegate的一部分)才能在位置管理器检索当前位置时得到通知

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last{
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.map.setRegion(region, animated: true)
    }
}
@H_404_7@

注意:如果目标是iOS 8或更高版本,则必须在Info.plist中包括NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription键,才能使定位服务正常工作。

解决方法

我正在学习如何使用新的Swift语言(只有Swift,没有Objective-C)。为此,我想用地图(MKMapView)做一个简单的视图。我想查找并更新用户的位置(例如在Apple
Map应用程序中)。

我试过了,但是什么也没发生:

import MapKit
import CoreLocation

class MapView : UIViewController,CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        if (CLLocationManager.locationServicesEnabled())
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    }
}

请你帮助我好吗?

喜欢与人分享编程技术与工作经验,欢迎加入编程之家官方交流群!
import MapKit
import CoreLocation

class MapView : UIViewController,CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        if (CLLocationManager.locationServicesEnabled())
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    }
}

注意:如果目标是iOS 8或更高版本,则必须在Info.plist中包括NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription键,才能使定位服务正常工作。

我正在学习如何使用新的Swift语言(只有Swift,没有Objective-C)。为此,我想用地图(MKMapView)做一个简单的视图。我想查找并更新用户的位置(例如在Apple
Map应用程序中)。

我试过了,但是什么也没发生:

请你帮助我好吗?

注意:如果目标是iOS 8或更高版本,则必须在Info.plist中包括NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription键,才能使定位服务正常工作。

Swift 2022/1/1 18:17:39 有283人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶