ios - 如何使用 google Api 查找我周围的地方

标签 ios google-api google-places-api

我正在开发使用 Google API 的应用程序。我试图通过它找到我周围的地方。我正在使用下面的代码来获取数据,

-(void)fetchedData:(NSData *)responseData {
    //this is to parse out the json data
    NSError *error = nil; //create some error handling here
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    //I'm told the returned results from Google will be an array obtained from the NSDictionary object with the key "results"

    NSArray *places = [json objectForKey:@"results"];

    //display the data to the console for review
    NSLog(@" Google data:\n%@", places);

}

但它显示 json 状态 = 请求被拒绝。 任何帮助将不胜感激。

最佳答案

维沙尔,

您可以使用以下代码块来完成此操作:

    - (void) queryGooglePlaces: (NSString *) googleType
{

    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%@&types=%@&sensor=true&key=%@&language=%@", appDelegate.currentLatitude, appDelegate.currentLongitude, [radiusValueArray objectAtIndex:[[NSUserDefaults standardUserDefaults] integerForKey:@"selectedDistance"]], googleType, kGOOGLE_API_KEY, appDelegate.selectedLanguageCode];

    //Formulate the string as URL object.
    NSURL *googleRequestURL=[NSURL URLWithString:url];

    // Retrieve the results of the URL.
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
        if(data == nil)
        {
            [placeTableView reloadData];
            [SVProgressHUD dismiss];
        }
        else
        {
            [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
        }
    });
}

- (void) queryGooglePlaces_WithNextPage
{
    // Build the url string we are going to sent to Google. NOTE: The kGOOGLE_API_KEY is a constant which should contain your own API key that you can obtain from Google. See this link for more info:

    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?pagetoken=%@&location=%f,%f&radius=%@&sensor=true&key=%@", nextPageToken, appDelegate.currentLatitude, appDelegate.currentLongitude, [radiusValueArray objectAtIndex:[[NSUserDefaults standardUserDefaults] integerForKey:@"selectedDistance"]], kGOOGLE_API_KEY];

    //Formulate the string as URL object.
    NSURL *googleRequestURL=[NSURL URLWithString:url];

    // Retrieve the results of the URL.
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
        if(data == nil)
        {
            [placeTableView reloadData];
            [SVProgressHUD dismiss];
        }
        else
        {
            [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
        }
    });
}

- (void)fetchedData:(NSData *)responseData
{
    //parse out the json data
    NSError* error;
    NSDictionary *json = [NSJSONSerialization
                          JSONObjectWithData:responseData

                          options:kNilOptions
                          error:&error];

    //The results from Google will be an array obtained from the NSDictionary object with the key "results".

    if(isNextPageAvailable == FALSE)
        [appDelegate.placesArray removeAllObjects];

    NSArray *placesTemp = [json objectForKey:@"results"];

    if([json valueForKey:@"next_page_token"] != nil)
    {
        nextPageToken = [json valueForKey:@"next_page_token"];
        isNextPageAvailable = TRUE;
    }
    else
    {
        nextPageToken = @"";
        isNextPageAvailable = FALSE;
    }


    for(int i=0;i<[placesTemp count];i++)
    {
        NSMutableDictionary *placeDictionary = [[NSMutableDictionary alloc] initWithDictionary:[placesTemp objectAtIndex:i]];

        double lat1 = appDelegate.currentLatitude;
        double long1 = appDelegate.currentLongitude;
        double lat2 = [[[[placeDictionary objectForKey:@"geometry"] objectForKey:@"location"] valueForKey:@"lat"] doubleValue];
        double long2 = [[[[placeDictionary objectForKey:@"geometry"] objectForKey:@"location"] valueForKey:@"lng"] doubleValue];

        CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
        CLLocation *location2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];

        [placeDictionary setValue:[NSString stringWithFormat:@"%f",[location1 distanceFromLocation:location2]] forKey:@"distance"];

        [appDelegate.placesArray addObject:placeDictionary];
    }

    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
        if ([obj1 floatValue] < [obj2 floatValue])
            return NSOrderedAscending;
        else
            return NSOrderedDescending;
    }];

    NSArray *sortedArray = [appDelegate.placesArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [appDelegate.placesArray removeAllObjects];
    [appDelegate.placesArray addObjectsFromArray:sortedArray];

    [self showPoweredbyGoogle];

    [placeTableView reloadData];
    [SVProgressHUD dismiss];

//    [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(reloadTableNow) userInfo:nil repeats:NO];

    //Plot the data in the places array onto the map with the plotPostions method.
    //    [self plotPositions:placesArray];
}

- (void) queryGooglePlaceDetail
{
    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/details/json?reference=%@&sensor=false&key=%@&language=%@", [[appDelegate.placesArray objectAtIndex:selectedPlaceIndex] valueForKey:@"reference"], kGOOGLE_API_KEY, appDelegate.selectedLanguageCode];

    //Formulate the string as URL object.
    NSURL *googleRequestURL=[NSURL URLWithString:url];

    // Retrieve the results of the URL.
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];

        if(data == nil)
        {
            [SVProgressHUD dismiss];
        }
        else
        {
            [self performSelectorOnMainThread:@selector(fetchedDetailPlaceData:) withObject:data waitUntilDone:YES];
        }
    });
}

- (void)fetchedDetailPlaceData:(NSData *)responseData
{
    //parse out the json data
    NSError* error;
    NSDictionary *json = [NSJSONSerialization
                          JSONObjectWithData:responseData

                          options:kNilOptions
                          error:&error];

    NSDictionary *detailTempDic = [[NSMutableDictionary alloc] initWithDictionary:[json objectForKey:@"result"]];
    [detailTempDic setValue:[[appDelegate.placesArray objectAtIndex:selectedPlaceIndex] valueForKey:@"distance"] forKey:@"distance"];

    [SVProgressHUD dismiss];

    [self performSegueWithIdentifier:@"Detail_Place_Push" sender:detailTempDic];
}

在这里,您必须传递来自 Google 地方信息的不同类型的对象,例如 atm、机场、餐厅、银行、医院、学校。

            [self queryGooglePlaces:[googlePlaceTypeArray objectAtIndex:SharedManager.selectedPlaceCategoryIndex]];

谢谢, 此致, 古普利特

关于ios - 如何使用 google Api 查找我周围的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25807163/

相关文章:

ios - 为什么我在尝试从 iOS 应用程序获取 google+ 个人资料图片时收到错误代码 403?

google-maps - Google Places API Web 服务的使用速度是发出请求的速度的 10 倍

ios - 一个属性字符串如数组

ios - NSDateFormatter 没有返回正确的日期

javascript - 如何管理 Google 登录 session (Google 登录 JavaScript 客户端)

python - 谷歌 API : getting Credentials from refresh token with oauth2client. 客户端

java - 限制 Android Google Places API 仅搜索给定区域

ios - 升级到 Xcode 8 和 Swift 3.0 后使用 Google Places iOS SDK 出现无法解释的异常

ios - 苹果的音乐应用程序如何定义用于文本的颜色以使其可读?

ios - 快速错误线程 1 : EXC_BAD_INSTRUCITON