如何在iPhone中找到银行,餐厅等最近的位置

时间:2011-07-29 11:19:53

标签: iphone cllocationmanager

我正在制作一个应用程序,其中我获取当前位置,名称和地址,纬度和经度,但如何找到最近的地方,如银行,餐厅,巴士站附近我当前位置的iPhone。

3 个答案:

答案 0 :(得分:2)

您可以像这样使用Google的服务,并在每次更改pointOfInterest字符串的循环中调用它:

CLLocationCoordinate2D coordinate = location.coordinate;
NSString *pointOfInterest = @"banks";
NSString *URLString = [NSString stringWithFormat:@"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=small&sll=%f,%f&q=%@",coordinate.latitude,coordinate.longitude, pointOfInterest];

URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];

// Perform request and get JSON back as a NSData object
NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if(error != nil) {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" 
                                                         message:[error localizedDescription] 
                                                        delegate:self 
                                               cancelButtonTitle:@"Done" 
                                               otherButtonTitles:nil] autorelease]; 
        [alert show];
}
else {
// Get JSON as a NSString from NSData response
    NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    //Return the values in NSDictionary format  
    SBJsonParser *parser = [[SBJsonParser alloc] init];

    NSDictionary *jsonResponse = [parser objectWithString:jsonString error:nil];
    NSDictionary *responseData = [jsonResponse objectForKey:@"responseData"];
    NSArray *results = [responseData objectForKey:@"results"];
}

您可以在此处获取JSON API:

https://github.com/stig/json-framework/

答案 1 :(得分:0)

您需要一个API来提供这些东西,标准SDK中没有。

答案 2 :(得分:0)

您应该有一个代表银行,餐馆或公共汽车的对象(示例中的站点)。您可能希望它实现MKAnnotation协议,因为您可能希望将它们添加到MKMapView。这些对象中的每一个都需要一个坐标属性(CLLocationCoordinate2D)。当我做这样的事情时,我还添加了一个距离属性(CLLocationDistance)。在viewcontroller中实例化这些对象时,您需要将它们添加到数组中。

现在,当用户的应用程序更新时,您可以让每个对象计算从该位置到自身的距离。

例如:

- (void)calculateDistance:(CLLocation *)location {
    CLLocation *stationLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    distance = [location distanceFromLocation:stationLocation];
    [stationLocation release];
}

一旦让每个物体计算出它的距离,你现在可以按距离对物体进行排序。

[stations sortUsingSelector:@selector(compareDistance:)]

这要求您的对象实现此方法:

- (NSComparisonResult)compareDistance:(Station *)aStation {
    if (distance < aStation.distance) return NSOrderedAscending;
    if (distance > aStation.distance) return NSOrderedDescending;
    return NSOrderedSame;
}

现在你应该让你的数组中的对象代表银行等按距离排序。

[stations objectAtIndex:0]将关闭您的位置。