两个lat长度之间的距离错误

时间:2013-11-12 11:30:48

标签: ios objective-c cllocation cllocationdistance

我想在两个地点之间找到距离。我使用下面的代码

获得两个位置的纬度和经度
-(void)getLatLongOfLoac:(NSString *)locStr{
    locStr = [locStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *geocodeUrl = [NSString stringWithFormat:@"%@://maps.google.com/maps/api/geocode/json?address=%@&sensor=false", 1 ? @"http" : @"https", locStr];

    ASIFormDataRequest *request   =  [ASIFormDataRequest requestWithURL:[NSURL URLWithString:geocodeUrl]];
    [request setRequestMethod:@"GET"];
    [request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestWentWrong:)];
    [request setDelegate:self];
    [request startAsynchronous];

}

-(void)requestDone:(ASIHTTPRequest *)request{
    NSString *responseString = [request responseString];
    SBJsonParser *json          = [[SBJsonParser alloc] init];
    NSError *jsonError          = nil;
    NSDictionary *parsedJSON    = [json objectWithString:responseString error:&jsonError];

   if(self.locationTableView.tag == 0){
      self.latlongForPicUp = [[[[parsedJSON valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"] valueForKey:@"location"];
   }
   else{
       self.latlongForDropOff = [[[[parsedJSON valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"] valueForKey:@"location"];
   }

}

并在两个位置之间获得距离我使用下面的代码

CLLocation *locA = [[CLLocation alloc] initWithLatitude:[[self.latlongForDropOff valueForKey:@"lat"] floatValue]longitude:[[self.latlongForDropOff valueForKey:@"lng"] floatValue]];

CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[self.latlongForPicUp valueForKey:@"lat"] floatValue] longitude:[[self.latlongForPicUp valueForKey:@"lng"]floatValue ]];

   // CLLocationDistance distance = [locA distanceFromLocation:locB];
//float distInMile = 0.000621371192 * [locA distanceFromLocation:locB];
NSString *distance = [ NSString stringWithFormat:@"%f",[locA distanceFromLocation:locB]];

它给了我一个非常大的价值,比如8749107.212873,在转换到它的里程之后,即使它有几千个,但这两个地方距离它只有20公里。

代码有问题吗?

2 个答案:

答案 0 :(得分:4)

创建第二个CCLocation时,您设置的纬度和经度是错误的:

你在做:

CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[self.latlongForPicUp valueForKey:@"lng"] floatValue] longitude:[[self.latlongForPicUp valueForKey:@"lat"]floatValue ]];

你应该这样做:

CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[self.latlongForPicUp valueForKey:@"lat"] floatValue] longitude:[[self.latlongForPicUp valueForKey:@"lng"]floatValue ]];

您正在交换价值。

答案 1 :(得分:0)

您是否注意到您正在设置

[[self.latlongForPicUp valueForKey:@"lng"] floatValue] for latitude and [[self.latlongForPicUp valueForKey:@"lat"]floatValue ]];? 

不会

[[self.latlongForPicUp valueForKey:@"lat"] floatValue] for latitude and [[self.latlongForPicUp valueForKey:@"lng"] floatValue] for longitude?

对于纬度和经度,我建议使用double而不是float,因为它更准确。在我看来,你应该尝试一下,看看会发生什么。