• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-12 11:49:58 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在开发使用 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap