iOS 高德地图定位并进行周边搜索
生活随笔
收集整理的這篇文章主要介紹了
iOS 高德地图定位并进行周边搜索
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
項目需要實現仿微信朋友圈可定位、搜索附近位置的功能:
?
實現方法
第1步,集成SDK(這里使用 CocoaPods 安裝)
pod 'AMapSearch' #地圖SDK搜索功能 pod 'AMapLocation' #定位SDK?
第2步,引入頭文件
#import <AMapFoundationKit/AMapFoundationKit.h> #import <AMapLocationKit/AMapLocationKit.h> #import <AMapSearchKit/AMapSearchKit.h>?
第3步,配置Key
在調用定位時,需要添加Key,需要注意的是請在 SDK 任何類的初始化以及方法調用之前設置正確的 Key。
[AMapServices sharedServices].apiKey = @"b5a84655e2cef54d488e990287d26bb9";?
第4步,更改info.plist
在info.plist的字段添加定位權限的申請,配置方式請參考手動部署部分說明。
?
第5步,配置后臺定位
?
第6步,代碼實現
#import "SearchSitesController.h"@interface SearchSitesController () <UITextFieldDelegate,AMapLocationManagerDelegate,AMapSearchDelegate>@property (nonatomic,strong) UITextField *searchTxt;//搜索框@property (nonatomic,assign) BOOL isSearchAround;@property (nonatomic,strong) NSMutableArray *addressArray;//搜索到的地址數組@property (nonatomic,strong) AMapLocationManager *locationManager;//定位管理@property (nonatomic,strong) AMapSearchAPI *searchAPI;//搜索類@property (nonatomic,strong) CLLocation *location;//當前定位的位置@property (nonatomic,copy) NSString *currentCity;//當前城市@end@implementation SearchSitesController#pragma mark - 懶加載- (NSMutableArray *)addressArray {if (!_addressArray) {_addressArray = [NSMutableArray array];}return _addressArray; }- (AMapLocationManager *)locationManager {if (!_locationManager) {_locationManager = [[AMapLocationManager alloc] init];[_locationManager setDelegate:self];[_locationManager setAllowsBackgroundLocationUpdates:YES];//iOS 9(不包含iOS 9) 之前設置允許后臺定位參數,保持不會被系統掛起[_locationManager setPausesLocationUpdatesAutomatically:NO];//iOS 9(包含iOS 9)之后新特性:將允許出現這種場景,同一app中多個locationmanager:一些只能在前臺定位,另一些可在后臺定位,并可隨時禁止其后臺定位。if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {_locationManager.allowsBackgroundLocationUpdates = YES;}}return _locationManager; }- (AMapSearchAPI *)searchAPI {if (!_searchAPI) {_searchAPI = [[AMapSearchAPI alloc] init];_searchAPI.delegate = self;}return _searchAPI; }- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view from its nib.self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:nil action:nil];//搜索框_searchTxt = [HELPER textFieldWithSuperView:self.view textAlignment:NSTextAlignmentLeft fontSize:14 textColor:TITLE_BLACK backgroundColor:RGB(243, 244, 246) placeholder:@"搜索地點" placeholderColor:PLACEHOLDER_COLOR placeholderFont:14 andMasonryBlock:^(MASConstraintMaker * _Nonnull make) {make.left.equalTo(@11);make.right.equalTo(@-55);make.height.equalTo(@31);make.top.equalTo(@(10));}];_searchTxt.delegate = self;_searchTxt.layer.cornerRadius = 31/2;_searchTxt.layer.masksToBounds = YES;_searchTxt.clearButtonMode = UITextFieldViewModeWhileEditing;_searchTxt.leftView = [[UIView alloc]initWithFrame:FRAME(0, 0, 35, 35)];_searchTxt.leftViewMode = UITextFieldViewModeAlways;[HELPER imageViewWithSuperView:_searchTxt.leftView backgroundColor:COLOR(clearColor) image:IMG(@"icon_search") andMasonryBlock:^(MASConstraintMaker * _Nonnull make) {make.center.equalTo(self.searchTxt.leftView);}];[_searchTxt addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];//取消按鈕[HELPER buttonWithSuperView:self.view andNormalTitle:@"取消" andNormalTextColor:PLACEHOLDER_COLOR andTextFont:16 andNormalImage:nil andCornerRadius:0 backgroundColor:COLOR(clearColor) addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside andMasonryBlock:^(MASConstraintMaker * _Nonnull make) {make.centerY.equalTo(self.searchTxt.mas_centerY);make.left.equalTo(self.searchTxt.mas_right).offset(5);make.right.equalTo(@-5);}];//分割線[HELPER imageViewWithSuperView:self.view backgroundColor:COLOR(groupTableViewBackgroundColor) image:nil andMasonryBlock:^(MASConstraintMaker * _Nonnull make) {make.height.equalTo(@1);make.left.right.equalTo(@0);make.top.equalTo(self.searchTxt.mas_bottom).offset(10);}];//設置tableViewself.mainTableView = [self tableViewWithSuperView:self.view style:UITableViewStylePlain backgroundColor:COLOR(clearColor) target:self andMasonryBlock:^(MASConstraintMaker * _Nonnull make) {make.left.right.bottom.equalTo(@0);make.top.equalTo(self.searchTxt.mas_bottom).offset(11);}];self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;self.mainTableView.separatorColor = COLOR(groupTableViewBackgroundColor);//開始定位[self.locationManager startUpdatingLocation]; }#pragma mark - 點擊取消按鈕 - (void)cancelAction:(UIButton *)sender {[self.navigationController popViewControllerAnimated:YES]; }#pragma mark - AMapLocationManagerDelegate/* 當定位發生錯誤時,會調用代理的此方法 */ - (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {//定位錯誤LOG(@"定位?error = %@",error); }/* 位置更新回調 */ - (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {//經緯度LOG(@"location:{lat:%f; lon:%f}", location.coordinate.latitude, location.coordinate.longitude);self.location = location;//逆地理編碼[self reGoecodeWithLocation:location];//發起周邊搜索[self searchAroundWithKeywords:nil];//停止定位[self.locationManager stopUpdatingLocation]; }//逆地理編碼 - (void)reGoecodeWithLocation:(CLLocation *)location {AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];request.location =[AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];[self.searchAPI AMapReGoecodeSearch:request]; }//根據定位坐標或關鍵字進行周邊搜索 - (void)searchAroundWithKeywords:(NSString *)keywords{if (keywords.length == 0) { //未輸入關鍵字,則為POI周邊搜索self.isSearchAround = YES;//構造AMapPOIAroundSearchRequest對象,設置周邊搜索參數AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];request.location = [AMapGeoPoint locationWithLatitude:self.location.coordinate.latitude longitude:self.location.coordinate.longitude];//types屬性表示限定搜索POI的類別,默認為:餐飲服務|商務住宅|生活服務//POI的類型共分為20種大類別request.types = @"汽車服務|汽車銷售|汽車維修|摩托車服務|餐飲服務|購物服務|生活服務|體育休閑服務|醫療保健服務|住宿服務|風景名勝|商務住宅|政府機構及社會團體|科教文化服務|交通設施服務|金融保險服務|公司企業|道路附屬設施|地名地址信息|公共設施";request.sortrule = 0;request.requireExtension = YES;//發起周邊搜索請求[self.searchAPI AMapPOIAroundSearch:request];}else{ //輸入了關鍵字,則為搜索提示請求self.isSearchAround = NO;AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];tipsRequest.city = self.currentCity;//查詢城市默認為當前定位的城市tipsRequest.keywords = keywords;[self.searchAPI AMapInputTipsSearch:tipsRequest];} }#pragma mark - AMapSearchDelegate/* 逆地理編碼查詢回調函數 */ - (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {self.currentCity = response.regeocode.addressComponent.city;if (self.currentCity.length == 0) {self.currentCity = response.regeocode.addressComponent.province;}LOG(@"當前定位城市 = %@",self.currentCity); }/* 實現POI搜索對應的回調函數 */ - (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {[self.addressArray removeAllObjects];if (response.pois.count>0) {//將搜索出的POI結果保存到數組[self.addressArray addObjectsFromArray:response.pois];}else{[self.mainTableView tableViewShowMessage:@"無結果" forDataCount:0];}[self.mainTableView reloadData]; }/* 輸入提示查詢回調函數 */ - (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response {[self.addressArray removeAllObjects];if (response.tips.count>0) {//將搜索出的結果保存到數組[self.addressArray addObjectsFromArray:response.tips];}else{[self.mainTableView tableViewShowMessage:@"無結果" forDataCount:0];}[self.mainTableView reloadData]; }#pragma mark - <UITableViewDataSource,UITableViewDelegate>-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{return 1; }-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{return self.addressArray.count; }-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{NSString *identifier = @"cellID";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];if (cell == nil) {cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];}if (self.isSearchAround == YES) {//POI周邊搜索AMapPOI *poi = self.addressArray[indexPath.row];cell.textLabel.text = poi.name;cell.detailTextLabel.text = poi.address;}else{//輸入提示搜索AMapTip *tip = self.addressArray[indexPath.row];cell.textLabel.text = tip.name;cell.detailTextLabel.text = tip.address;}return cell; }-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{return 50; }-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{return 0.01; }-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{return 0.01; }-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{return nil; }-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{return nil; }-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{[tableView deselectRowAtIndexPath:indexPath animated:YES]; }#pragma mark - 監聽textField值改變 - (void)textFieldValueChanged:(UITextField *)textField {[self searchAroundWithKeywords:textField.text]; }#pragma mark - UITextFieldDelegate - (BOOL)textFieldShouldReturn:(UITextField *)textField {[self.view endEditing:YES];return YES; }@end?
總結
以上是生活随笔為你收集整理的iOS 高德地图定位并进行周边搜索的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中日期如何转换_java如何转换
- 下一篇: 一加5android auto,一加5氧