谷歌地图、高德地图 搜索API使用方法及遇到的坑

959 阅读4分钟

#苹果地图. 直接上代码,传入搜索的文本:searchString 和搜索范围即可。

+ (void)AMapSearchLocationWithSearchStr:(NSString *)SearchString searchRegion:(MKCoordinateRegion )region result:(SearchResult)searchResult { 
    MKLocalSearchRequest * request = [[MKLocalSearchRequest alloc]init];
    request.region = region ;
    request.naturalLanguageQuery = SearchString ;
    MKLocalSearch *ser = [[MKLocalSearch alloc]initWithRequest:request];
    [ser startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSArray *array = [NSArray arrayWithArray:response.mapItems];
            NSMutableArray *placeArr = [NSMutableArray array];
            for (int i=0; i<array.count; i++) {
                MKMapItem * item=array[i];
                
                DVGmapPlaceModel *placeModel = [[DVGmapPlaceModel alloc]init];
                
                NSString *addressString =  ABCreateStringWithAddressDictionary(item.placemark.addressDictionary, NO);
                placeModel.short_address = addressString;
                placeModel.location = item.placemark.coordinate;
                
                NSLog(@"addressString---%@",addressString);

                [placeArr addObject:placeModel];
            }
            searchResult(YES, placeArr);

        }else {
            searchResult(NO, nil);
        }
        
    }];
}

#高德地图 高德地图相关位置搜索有两种方法。 ##1.webAPI (建议使用,返回值中就包含了 address 和 location, 若使用客户端api.则返回的plceID,需再进行一次lookup请求才能得到location.)

+ (void)googleMapWebSearchLocationWithSearchStr:(NSString *)SearchString location:(CLLocationCoordinate2D) coordinate  radius:(float)radius result:(SearchResult)searchResult {
    
    NSString *apiStr = @"AIzaSyBlW3RlTzQlYHRnxv8j5iGt5RkJBPUvJ-g";  //API For Web
    
    NSString *urlStr = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/textsearch/json?query=%@&location=%f,%f&radius=%f&key=%@",SearchString,coordinate.latitude,coordinate.longitude,radius,apiStr];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray *resultArr = [dataDict exitObjectForKey:@"results"];
            
            __block  NSMutableArray *placeArr = [NSMutableArray array];
            [resultArr enumerateObjectsUsingBlock:^(NSDictionary *infoDict, NSUInteger idx, BOOL * _Nonnull stop) {
                
                DVGmapPlaceModel *placeModel = [[DVGmapPlaceModel alloc]init];
                NSString *formatted_address = [infoDict exitObjectForKey:@"formatted_address"];
                NSString *nameStr = [infoDict exitObjectForKey:@"name"];
                NSString *fullAddress = [NSString stringWithFormat:@"%@, %@",nameStr,formatted_address];
                placeModel.short_address = [self getShortAddressWithAddress:fullAddress];
                placeModel.formatted_address = fullAddress;
                
                NSDictionary *localDict = [infoDict exitObjectForKey:@"geometry"];
                CLLocationDegrees lat = [[localDict exitObjectForKey:@"lat"] doubleValue];
                CLLocationDegrees lng = [[localDict exitObjectForKey:@"lng"] doubleValue];
                placeModel.location = CLLocationCoordinate2DMake(lat, lng);
                
                NSString *placeId = [infoDict exitObjectForKey:@"place_id"];
                placeModel.placeID = placeId;
                [placeArr addObject:placeModel];
                
                NSLog(@"%@-%@---%f>>>%f==--%@",placeModel.short_address,placeModel.formatted_address,placeModel.location.latitude,placeModel.location.longitude,placeModel.placeID);
            }];
            
            searchResult(YES, placeArr);
        }else {
            searchResult(NO, nil);
            NSLog(@"Error---%@",[error localizedDescription]);
        }
        
    }];
    [task resume];
    
}

返回的内容有:具体名称 和经纬度坐标, placeID(通过id可以确定某个坐标,这儿已经返回其坐标了所以不使用)。

使用注意点: NSString *apiStr = @"AIzaSyBlW3RlTzQlYHRnxv8j5iGt5RkJBPUvJ-g";  //API For Web 此处是你所申请的APIKey, API for web 和 API for iOS是不一样的,既然用的是web接口就要用 API for web!

##iOS手机端API

+ (void)googleMapSearchLocationWithSearchStr:(NSString *)SearchString searchBounds:(GMSCoordinateBounds *)bounds result:(SearchResult)searchResult {
    
    [GMSPlacesClient provideAPIKey:@"AIzaSyD3NJirvXWjBsVo8SPzOOqRW0F_EDydex0"]; //API For iOS

    GMSPlacesClient *client = [GMSPlacesClient sharedClient];
    GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
    filter.type = kGMSPlacesAutocompleteTypeFilterNoFilter;

   [client autocompleteQuery:SearchString bounds:bounds filter:filter callback:^(NSArray<GMSAutocompletePrediction *> * _Nullable results, NSError * _Nullable error) {
       if (error == nil) {
           NSMutableArray *placeArr = [NSMutableArray array];
           for (GMSAutocompletePrediction* result in results) {
               NSLog(@"Result '%@' with placeID %@", result.attributedFullText.string, result.types);
               DVGmapPlaceModel *placeModel = [[DVGmapPlaceModel alloc]init];
               placeModel.placeID = result.placeID;
               placeModel.formatted_address = [self getShortAddressWithAddress:result.attributedFullText.string];
               
               [placeArr addObject:placeModel];
           }
           
           searchResult(YES,placeArr);
       }else {
           NSLog(@"Error-------%@",[error localizedDescription]);
           searchResult(NO,nil);
       }
   }];

}
//根据PlaceID获取坐标经纬度。
+ (void)gooleMapLookUpPlaceID:(NSString *)placeID  lookupRsult:(LookUpResult) lookUpResult {
    [GMSPlacesClient provideAPIKey:@"AIzaSyD3NJirvXWjBsVo8SPzOOqRW0F_EDydex0"];
    
    GMSPlacesClient *client = [GMSPlacesClient sharedClient];
    GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
    filter.type = kGMSPlacesAutocompleteTypeFilterNoFilter;
    
    [client lookUpPlaceID:placeID callback:^(GMSPlace * _Nullable result, NSError * _Nullable error) {
        if (error == nil) {
            NSLog(@"Result '%f-----%f' with placeID %@", result.coordinate.latitude,result.coordinate.longitude, result.placeID);
            
            DVGmapPlaceModel *placeModel = [[DVGmapPlaceModel alloc]init];
            placeModel.placeID = result.placeID;
            placeModel.location = result.coordinate;
            
            lookUpResult(YES,placeModel);
            
        }else {
            lookUpResult(NO,nil);
        }

    }];

}

使用注意点: 1.在调用autocompleteQuery:SearchString方法之前必须调用:[GMSPlacesClient provideAPIKey:@"AIzaSyD3NJirvXWjBsVo8SPzOOqRW0F_EDydex0"]; //API For iOS方法,否者会报错: ** Error-------The operation couldn’t be completed. An internal error occurred in the Places API library. If you believe this error represents a bug, please file a report using the instructions on our community and support page (https://developers.google.com/places/support).** (笔者第一次做的时候在这儿卡了很久); 2.再次强调 API for iOS 与 API for web 不是同一个。

最后上传一份自己的封装: [git地址]