如何在Swift中设置自定义距离过滤器?

时间:2016-12-08 16:13:00

标签: ios swift mapkit

我是Swift的新手,我尝试使用这个

  

How to set accuracy and distance filter when using MKMapView

不知道为什么这段代码不起作用:

//start  mehtod out of scope
lazy var locationManager: CLLocationManager! = {
    let locationManager = CLLocationManager()


    //configeration for  user location access
    //The delegate object to receive update events.
    locationManager.delegate = self
    //The receiver does its best to achieve the requested accuracy
    //locationManager.desiredAccuracy = kCLLocationAccuracyBest
     self.locationManager.distanceFilter = 10.0
    //Requests permission to use location services while the app is in the foreground
    locationManager.requestWhenInUseAuthorization()
    //allow update notification when apps stay on background
    locationManager.allowsBackgroundLocationUpdates = true

    return locationManager
}() 

当我选择它时它工作正常:

locationManager.desiredAccuracy = kCLLocationAccuracyBest

所以我想要的是什么:

如果用户改变位置,我想在每250米后获得LAT和LONG,然后连续15分钟调用一个方法

 pushLocation(lat:double,long:double)

2 个答案:

答案 0 :(得分:4)

这是我正在使用的代码 - 全部在Swift 3.0中。

locationManager的这种设置将处理你所追求的距离过滤和准确度:

lazy var locationManager: CLLocationManager = {
    [unowned self] in
    var _locationManager = CLLocationManager()
    _locationManager.delegate = self
    _locationManager.desiredAccuracy = [Your Value For trackingAccuracy - see below]
    _locationManager.distanceFilter = [Your Value For the filter i.e., 250 for 250 meters]
    _locationManager.allowsBackgroundLocationUpdates = true
    _locationManager.pausesLocationUpdatesAutomatically = false 
    _locationManager.activityType = .fitness
    return _locationManager
    }()

准确度设置来自位置管理器中的预定义设置,例如,kCLLocationAccuracyNearestTenMeters或kCLLocationAccuracyHundredMeters。

即使您的应用不在前台,允许后台更新的选项也可让您获得新积分。如果手机不时停止移动,则必须自动关闭暂停 - 否则,如果您的用户停止休息5分钟并且不会重新打开,它将自动关闭捕获 - 您必须在重置时重置这些停顿重做。

授权状态应在下面的单独检查中处理,以便您可以申请授权(如果尚未提供):

    if CLLocationManager.authorizationStatus() != .authorizedAlways     // Check authorization for location tracking
    {
        locationManager.requestAlwaysAuthorization()                    // Will callbackdidChange... once user responds
    } else {
        locationManager.startUpdatingLocation()
    }

由于获得授权有延迟,如果您必须提出请求,则需要等待请求它开始更新位置,直到您从locationManager收到回复,您可以执行以下操作:

@nonobjc func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status
    {
    case .authorizedAlways:
        locationManager.startUpdatingLocation()

    default:
        [Whatever you want to do - you can't get locations]
    }
}

我需要。一直以来,你可以根据你的使用情况擅自离开.authorizedWhenInUse。

我根据检查locationManager传回给我的位置的准确度字段,添加了一个额外的过滤精度。请注意,有单独的水平和垂直精度值(以米为单位的置信距离);如果你想使用高程值,你需要注意第二个准确度值,因为在iPhone中,高程本质上不太准确。

我还检查在前一点之后捕获了新点 - 有时会出现序列值不正确并指示“有问题”的值。我已经读过你可能会得到小于0的准确度值来表示问题,所以你可能想在使用该位置之前检查一下,尽管我还没有看到这个问题。这是代码:

// Called back by location manager - passes arrays of new CLLocation points captured. With distanceFilter set to 250, this will get called for a change of 250M.  You'll want to save the value for your timed pushLocation function.

// This function needs to be trim as it continues to be called when TrailHead is in the background and, if 
// we take too long we'll get killed by iOS.

var savePosition: CLLocationCoordinate2D?
private var latestTimeProcessed = Date()  // Initialize to ensure any point accepted received after initialization

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    for location in locations {
        if latestTimeProcessed.compare(location.timeStamp) == .orderedAscending        // Out of seq indicates a locationManager problem - discard
            && location.horizontalAccuracy < [Whatever accuracy limit you want to use]    // Applying a user-selected quality filter
        {
            latestTimeProcessed = location.timeStamp      // Used to discard any earlier timestamped points returned by the location manager
            [PROCESS THE POSITION HERE - E.G.]

            savePosition = locations.last

        }
    }
}

就推送更新而言,我会添加一个计时器

private var myTimer: Timer? = nil  
private var longInterval = 900.0     // 900 seconds = 15 minutes

override func viewDidLoad()
{
    ....
        myTimer = Timer(timeInterval: timerInterval, target: myself, selector: #selector(myself.pushLocation), userInfo: nil, repeats: true)
        RunLoop.current.add(myTimer!, forMode: RunLoopMode.commonModes)
    ....
}

pushLocation(lat:double,long:double){
    [Use savePosition.latitude, savePosition.longitude]
}

希望这会有所帮助......

答案 1 :(得分:1)

根据您的问题,您希望在每次 250米之后获得LATLONG? 因此,对于此,Objective C Code :(感谢链接:https://stackoverflow.com/a/39996989/3400991

首先调用此方法并存储此新位置,然后当任何(LAT,LONG)与此存储位置匹配时,您需要连续查找其他纬度和长度,这意味着您已经行进了250米:

这是SWIFT3.0代码:

func locationByMovingDistance(distanceMeters: Double, withBearing bearingDegrees: CLLocationDirection) -> CLLocation {
    let distanceRadians: Double = distanceMeters / (6372797.6)
        // earth radius in meters
    let bearingRadians: Double = bearingDegrees * M_PI / 180
    var lat1: Float = self.coordinate.latitude * M_PI / 180
    var lon1: Float = self.coordinate.longitude * M_PI / 180
    var lat2: Float = asin(sin(lat1) * cos(distanceRadians) + cos(lat1) * sin(distanceRadians) * cos(bearingRadians))
    var lon2: Float = lon1 + atan2(sin(bearingRadians) * sin(distanceRadians) * cos(lat1), cos(distanceRadians) - sin(lat1) * sin(lat2))
    return CLLocation(latitude: lat2 * 180 / M_PI, longitude: lon2 * 180 / M_PI)
}

如果您有任何进一步的问题,请随时发表评论。希望它有所帮助。

相关问题