0

我想获得两个位置之间的距离。我正在使用以下代码获取两个位置的纬度和经度

-(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 公里。

代码有问题吗?

4

2 回答 2

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 ]];

您正在交换值。

于 2013-11-12T11:33:31.010 回答
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,因为这样更准确。在我看来,你应该尝试一下,看看会发生什么。

于 2013-11-12T13:15:31.150 回答