Для расчета расстояния понадобятся два CLLocation
(скажем, newLocation
и oldLocation
). Вы можете рассчитать расстояние между этим двумя точками с помощью:
let distance = Double(newLocation.distanceFromLocation(oldLocation))
После этого просто добавьте вам логику, чтобы решить, когда, чтобы отправить уведомление:
if distance > myMinimum distance{
NSNotificationCenter.defaultCenter().postNotificationName("location", object: self)
}
Примечание, это кратчайшее расстояние вычисляется между к точкам (прямая линия) он не вычисляет расстояние маршрута.
Если вы хотите, чтобы вычислить расстояние маршрута между двумя точками необходимо использовать MKDirectionsRequest, это вернет вам один или много, маршруты из точки А в точку Б с пошаговой инструкцией:
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
функция может быть легко изменена, чтобы получить два места и вернуть расстояние и любую другую необходимую информацию.
Я надеюсь, что это поможет!
Возможный дубликат [Рассчитать общее количество путешествованных расстояний iOS Swift] (http://stackoverflow.com/questions/28952747/calculate-total-traveled-distance-ios-swift) –
places.first и locations.last одинаковы , местоположения имеют только 1 элемент –
Вы не должны публиковать уведомление каждый раз, когда вы получаете обновление местоположения –