Рассчитать расстояние при ходьбе между фиксированной точкой и моим текущим местоположением в iOS - PullRequest
0 голосов
/ 02 июля 2018

Мне нужно рассчитать расстояние между двумя точками в iOS и целью c. Мое единственное местоположение зафиксировано в точке, и когда я иду, я должен вычислить расстояние между моей текущей позицией и фиксированной точкой. Я использовал distanceFromLocation метод, но я не получаю значение расстояния ближе. Я просмотрел несколько статей и несколько решений StackOverflow, но ни одна из них не дала мне должного результата.

Ниже приведен код, который я использовал, а в коде currentLocation и destinationLocation - свойства для хранения широты и долготы местоположений. DestinationLocation всегда является фиксированным местоположением, а currentLocation постоянно меняется, когда я иду. Существует несколько UILabels для печати текущих и фиксированных значений широты и долготы. Я должен вычислять расстояние каждый раз между этими двумя точками. Когда я двигаюсь на половину или меньше метра, это показывает мне большое расстояние, которое также является непоследовательным. Не могли бы вы помочь мне, какую ошибку я здесь делаю? Есть ли другой способ добиться этого? Спасибо!

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *newLocation = locations.lastObject;
    self.currentLocation = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];

    if(self.destinationLocation == nil){
        self.destinationLocation = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
        self.destinationLatitude.text = [NSString stringWithFormat:@"%.8f", self.destinationLocation.coordinate.latitude];
        self.destinationLongitude.text = [NSString stringWithFormat:@"%.8f", self.destinationLocation.coordinate.longitude];
    }

    self.currentLatitude.text = [NSString stringWithFormat:@"%.8f", self.currentLocation.coordinate.latitude];
    self.currentLongitude.text = [NSString stringWithFormat:@"%.8f", self.currentLocation.coordinate.longitude];

    CLLocationDistance distance = [self.currentLocation distanceFromLocation:self.destinationLocation];
    self.gpsDistanceMeasurement.text = [NSString stringWithFormat:@"%.2f m", distance];
}

1 Ответ

0 голосов
/ 02 июля 2018

Вы можете использовать формулу haversine для расчета расстояния между двумя точками

swift 3.x

let Source = CLLocationCoordinate2D.init(latitude: lat, longitude: long)
let Destination = CLLocationCoordinate2D.init(latitude: lat, longitude: long)

func DistanceCalculator(Source:CLLocationCoordinate2D,Destination:CLLocationCoordinate2D) -> Double
{
    // HaverSine Formula to calculate Diastance On Sphere Refrences//https://www.movable-type.co.uk/scripts/latlong.html
    // Angle = sin2(∆Ø/2) + cosØ1 * cosØ2 * sin2(∆ø/2)
    // constant = 2 * atan2(√angle,√1-angle)
    // distance = R * c
    let Earth_Radius:Double = 6371 * 1000
    let LatDelta = self.DegreeToRad(Degree: (Destination.latitude - Source.latitude))
    let LongDelta = self.DegreeToRad(Degree: (Destination.longitude - Source.longitude))
    let latRad = self.DegreeToRad(Degree: Source.latitude)
    let longRad = self.DegreeToRad(Degree: Destination.latitude)

    let Angle = (sin(LatDelta/2) * sin(LatDelta/2)) + (cos(latRad) * cos(longRad) * sin(LongDelta/2) * sin(LongDelta/2))
    let constant = 2 * atan2(sqrt(Angle),sqrt(1-Angle))
    let Distance = Earth_Radius * constant
    return Distance
}


func DegreeToRad(Degree:Double) -> Double
{
    return Degree * (Double.pi / 180)
}
...