CLLocation Manager如何在一定距离后更新
我正在使用CLLocationManager didupdatelocations,如下所示:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { location = locations.last as? CLLocation NSNotificationCenter.defaultCenter().postNotificationName("location", object: self) }
这一切都运行正常但我只想发布通知,如果该位置距离原始位置一定距离。 我可以使用吗?
locations.first
并将其与locations.last进行比较,看起来只有当用户继续在城市中移动时才会更新原始内容。
要计算距离,您需要两个CLLocation
(比方说, newLocation
和oldLocation
)。 您可以使用以下方法计算这两个位置之间的距离:
let distance = Double(newLocation.distanceFromLocation(oldLocation))
之后只需添加逻辑来决定何时发布通知:
if distance > myMinimum distance{ NSNotificationCenter.defaultCenter().postNotificationName("location", object: self) }
注意 ,这是在点之间计算的最短距离(直线),它不计算路线距离。
如果要计算两点之间的路线距离,则需要使用MKDirectionsRequest,这将通过分步指令返回从A点到B点的一条或多条路线:
class func caculateDistance(){ var directionRequest = MKDirectionsRequest() var sourceCoord = CLLocationCoordinate2D(latitude: -36.7346287, longitude: 174.6991812) var destinationCoord = CLLocationCoordinate2D(latitude: -36.850587, longitude: 174.7391745) var mkPlacemarkOrigen = MKPlacemark(coordinate: sourceCoord, addressDictionary: nil) var mkPlacemarkDestination = MKPlacemark(coordinate: destinationCoord, addressDictionary: nil) var source:MKMapItem = MKMapItem(placemark: mkPlacemarkOrigen) var destination:MKMapItem = MKMapItem(placemark: mkPlacemarkDestination) directionRequest.setSource(source) directionRequest.setDestination(destination) var directions = MKDirections(request: directionRequest) directions.calculateDirectionsWithCompletionHandler { (response, error) -> Void in if error != nil { println("Error calculating direction - \(error.localizedDescription)") } else { for route in response.routes{ println("Distance = \(route.distance)") for step in route.steps!{ println(step.instructions) } } } } }
此示例代码将返回此信息:
Disntance Distance = 16800.0 Step by Step instructions Start on the route At the end of the road, turn left onto Bush Road Turn right onto Albany Expressway At the roundabout, take the first exit onto Greville Road toward 1, Auckland At the roundabout, take the third exit to merge onto 1 toward Auckland Keep left Take exit 423 onto Shelly Beach Road Continue onto Shelly Beach Road At the end of the road, turn right onto Jervois Road Turn left onto Islington Street Keep right on Islington Street Arrive at the destination
可以轻松修改该function以接收两个位置并返回距离和任何其他所需信息。
我希望能帮到你!
- Swift开发人员认证-帮助Cell Builders在应用程序升级中提升
- 使用AFNetworking的AFHTTPRequestOperation读取状态行(状态代码和原因短语)
- 使用Firebase Data Swift填充UITableViewController,Xcode 7
- TouchID错误代码:-1004 NSLocalizedDescription:用户交互是必需的
- swift:无法读取(本地)plist文件到操场上的字典
- iOS推送通知:如何检测当应用程序在后台时用户是否轻敲通知?
- 在故事板中使用自定义tableviewcell时,IBOutlet是零
- UITextfield becomeFirstResponder返回NO
- 为什么静态NSString泄漏?