从用户位置查找数组中的距离经度和纬度

时间:2014-12-15 21:02:28

标签: objective-c xcode localization parse-platform cllocationmanager

计算我的位置与从Parse.com上创建的数据库中下载数据的数组获得的坐标之间的距离时出现问题。我也想找到离我位置最近的距离。我使用的代码是:

    NSString *Lat = [[object objectForKey:@"Latitudine"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* Long = [[object objectForKey:@"Longitudine"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    Latdouble = [Lat doubleValue];
    Longdouble = [Long doubleValue];


    NSArray *locations = [NSArray arrayWithObjects:[[CLLocation alloc] initWithLatitude:Latdouble longitude:Longdouble], nil];

    NSLog(@"LOCATIONS COORDINATE: %@", locations);

    CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude];;
    CLLocation *closestLocation;
    CLLocationDistance smallestDistance = DBL_MAX;

    for (CLLocation *location in locations) {
        CLLocationDistance distance = [currentLocation distanceFromLocation:location];

        NSLog(@" ");
        NSLog(@"DIST: %f", distance);
        NSLog(@" ");

        if (distance < smallestDistance) {
            distance = smallestDistance;
            closestLocation = location;

            NSLog(@"CLOSEST LOCATION: %@ \n\n DISTANCE: %f", closestLocation, distance);
        }
    }

我在编译时得到这个结果:

2014-12-15 21:54:37.101 Veg[28614:263678] LOCATIONS COORDINATE: (
    "<+45.45592700,+11.05733500> +/- 0.00m (speed -1.00 mps / course -1.00) @ 12/15/14, 10:08:08 PM Central European Standard Time"
)
2014-12-15 21:54:37.101 Veg[28614:263678] DIST: 5172045.683883
2014-12-15 21:54:37.101 Veg[28614:263678]  
2014-12-15 21:54:37.102 Veg[28614:263678] CLOSEST LOCATION: <+45.43574900,+10.98694600> +/- 0.00m (speed -1.00 mps / course -1.00) @ 12/15/14, 9:54:37 PM Central European Standard Time 

 DISTANCE: 
17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687817154
04589535143824642343213268894641827684675467035375169860499105765512820762454900903893289440758685084551
33942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.00
0000

有什么问题?为什么我会获得这个巨大的价值?在此先感谢您的帮助

1 个答案:

答案 0 :(得分:1)

你有:

if (distance < smallestDistance) {
    distance = smallestDistance;
    closestLocation = location;

指定smallestDistance初始化为DBL_MAXdistance,因此smallestDistance永远不会改变。

你需要什么:

if (distance < smallestDistance) {
    smallestDistance = distance;
    closestLocation = location;

smallestDistance较小时,将distance更新为distance