OStack程序员社区-中国程序员成长平台

标题: ios - 如何使用 google Api 查找我周围的地方 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:49
标题: ios - 如何使用 google Api 查找我周围的地方

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

-(void)fetchedDataNSData *)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 status = Request Denied。 任何帮助将不胜感激。



Best Answer-推荐答案


维沙尔,

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

    - (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 performSelectorOnMainThreadselector(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 performSelectorOnMainThreadselector(fetchedData withObject:data waitUntilDone:YES];
        }
    });
}

- (void)fetchedDataNSData *)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)fetchedDetailPlaceDataNSData *)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 地方信息的不同类型的对象,例如自动取款机、机场、餐厅、银行、医院、学校。

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

谢谢, 此致, 古普里特

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






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4