iOS之集成谷歌地圖GoogleMap地圖選址(定位翎猛、搜索)功能

前言

最近在開發(fā)一款國外的APP中,需要用到谷歌地圖接剩,記錄下流程切厘。

1.申請谷歌賬號、創(chuàng)建應(yīng)用懊缺、獲取API key
2.項目導(dǎo)入SDK
3.配置plist
4.調(diào)用代理方法實現(xiàn)需求

一疫稿、申請谷歌賬號、創(chuàng)建應(yīng)用、獲取API key

谷歌地圖開放平臺地址:https://cloud.google.com/maps-platform/?hl=zh-CN

  1. 如果要查看谷歌地圖的開發(fā)文檔或者APP測試谷歌地圖遗座,都需要翻墻舀凛。
    免費的可以使試試 佛跳墻 ,網(wǎng)速也還可以途蒋。
    收費的 同學(xué)給推薦了一個socketpro猛遍,買了一個月,19元号坡,網(wǎng)速還可以懊烤。

  2. 申請賬號流程此處省略。

3.創(chuàng)建項目,創(chuàng)建完項目 切換到該項目下宽堆,創(chuàng)建憑證 獲取apikey, 配置api, 配置的時候 選擇了2個api,Maps SDK for iOS是用來顯示地圖和定位奸晴,Places API 是用來POI檢索用的。

創(chuàng)建項目

創(chuàng)建憑證1

創(chuàng)建憑證2

獲取APIkey

配置API

二日麸、項目導(dǎo)入SDK

用的是cocopod 方式集成的寄啼,手動的 可以去官方文檔查看。

#谷歌地圖
pod'GoogleMaps'
pod'GooglePlaces'
  • GoogleMaps:顯示基本的定位功能代箭;
  • GooglePlaces:實現(xiàn)搜索功能墩划,官方文檔叫做地點自動完成;
  • GooglePlacePicker:是實現(xiàn)獲取某個POI的的詳細信息嗡综,比如名字乙帮、詳細地址、路線等),這個暫時沒用到极景,如果有需要 也導(dǎo)入即可察净。

三、配置plist

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>App需要獲取定位權(quán)限來選擇您的地址</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App需要獲取定位權(quán)限來選擇您的地址</string>

四盼樟、調(diào)用代理方法實現(xiàn)需求

1. 導(dǎo)入頭文件
#import <GoogleMaps/GoogleMaps.h>
#import <GooglePlaces/GooglePlaces.h>
#import <CoreLocation/CoreLocation.h>
2. AppDelegate 中的 application:didFinishLaunchingWithOptions 方法下 初始化配置

APIKEY_Google 是 在上面在谷歌后臺獲取的 APIKEY

[GMSServices provideAPIKey:APIKEY_Google]; 
[GMSPlacesClient provideAPIKey:APIKEY_Google];
3. 地圖顯示頁面代碼如下

JZLocationConverter 主要用來 國內(nèi)坐標(biāo)系的轉(zhuǎn)換
https://github.com/JackZhouCn/JZLocationConverter
APP 如果要測試谷歌地圖 手機必須要翻墻后才行氢卡,下面的代碼隱去了地址的展示,如果有需要自己添加

#import "HGBMapVC1.h"
#import <GoogleMaps/GoogleMaps.h>
#import <GooglePlaces/GooglePlaces.h>
#import <CoreLocation/CoreLocation.h>
#import "JZLocationConverter.h"

#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height
/*適配全面屏*/
#define StateBar_Height [[UIApplication sharedApplication] statusBarFrame].size.height
#define UI_navBar_Height (StateBar_Height == 44 ? 88.0 : 64.0) //適配iPhone x 導(dǎo)航高度
#define SafeAreaBottomHeight (StateBar_Height == 44 ? 34 : 0)  // 底部宏

@interface HGBMapVC1 ()<GMSMapViewDelegate,CLLocationManagerDelegate,GMSAutocompleteViewControllerDelegate>

@property (nonatomic,strong) GMSMapView *mapView ;
@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,assign) CLLocationCoordinate2D coordinate2D;
@property (nonatomic,assign) BOOL firstLocationUpdate ;
@property (nonatomic,strong) GMSMarker *marker;//大頭針
@property (nonatomic,strong) GMSPlacesClient * placesClient;//可以獲取某個地方的信息

@end

@implementation HGBMapVC1

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.title = @"選擇地址";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"搜索" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -5);
    [btn addTarget:self action:@selector(navRightClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    //設(shè)置地圖view晨缴,這里是隨便初始化了一個經(jīng)緯度译秦,在獲取到當(dāng)前用戶位置到時候會直接更新的
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:38.02 longitude:114.52 zoom:15];
    _mapView= [GMSMapView mapWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-UI_navBar_Height-70-SafeAreaBottomHeight) camera:camera];
    _mapView.delegate = self;
    _mapView.settings.compassButton = YES;//顯示指南針
//    _mapView.settings.myLocationButton = YES;
//    _mapView.myLocationEnabled = NO;
    [self.view addSubview:_mapView];
    
    
    /* 開始定位*/
    [self startLocation];
}
-(void)navRightClick{
    GMSAutocompleteViewController *autocompleteViewController = [[GMSAutocompleteViewController alloc] init];
    autocompleteViewController.delegate = self;
    [self presentViewController:autocompleteViewController animated:YES completion:nil];
}
- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        //定位功能可用
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;//設(shè)置定位精度
        _locationManager.distanceFilter = 10;//設(shè)置定位頻率,每隔多少米定位一次
        [_locationManager startUpdatingLocation];
    } else {
        //定位不能用
        [self locationPermissionAlert];
        [SVProgressHUD dismiss];
    }
}
#pragma mark - 系統(tǒng)自帶location代理定位
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"訪問被拒絕");
        [self locationPermissionAlert];
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"無法獲取位置信息");
    }
    [SVProgressHUD dismiss];
}
- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray *)locations {
    if(!_firstLocationUpdate){
        _firstLocationUpdate = YES;//只定位一次的標(biāo)記值
        // 獲取最新定位
        CLLocation *location = locations.lastObject;
        // 停止定位
        [_locationManager stopUpdatingLocation];
        //如果是國內(nèi)击碗,就會轉(zhuǎn)化坐標(biāo)系筑悴,如果是國外坐標(biāo),則不會轉(zhuǎn)換稍途。
        _coordinate2D = [JZLocationConverter wgs84ToGcj02:location.coordinate];
        //移動地圖中心到當(dāng)前位置
        _mapView.camera = [GMSCameraPosition cameraWithTarget:_coordinate2D zoom:15];

//        self.marker = [GMSMarker markerWithPosition:_coordinate2D];
//        self.marker.map = self.mapView;
        
        [self getPlace:_coordinate2D];
    }
}
-(void)mapViewDidFinishTileRendering:(GMSMapView *)mapView{
   
}
//地圖移動后的代理方法阁吝,我這里的需求是地圖移動需要刷新網(wǎng)絡(luò)請求,查找附近的店鋪
-(void)mapView:(GMSMapView*)mapView idleAtCameraPosition:(GMSCameraPosition*)position{
//    //點擊一次先清除上一次的大頭針
//    [self.marker.map clear];
//    self.marker.map = nil;
//    self.marker = [GMSMarker markerWithPosition:mapView.camera.target];
//    self.marker.map = self.mapView;
    [self getPlace:mapView.camera.target];
}
-(void)getPlace:(CLLocationCoordinate2D)coordinate2D{
    
    [[GMSGeocoder geocoder] reverseGeocodeCoordinate:CLLocationCoordinate2DMake(coordinate2D.latitude, coordinate2D.longitude) completionHandler:^(GMSReverseGeocodeResponse * _Nullable response, NSError * _Nullable error) {
        if(!error){
            GMSAddress* addressObj = response.firstResult;
            NSLog(@"coordinate.latitude=%f", addressObj.coordinate.latitude);
            NSLog(@"coordinate.longitude=%f", addressObj.coordinate.longitude);
            NSLog(@"thoroughfare=%@", addressObj.thoroughfare);
            NSLog(@"locality=%@", addressObj.locality);
            NSLog(@"subLocality=%@", addressObj.subLocality);
            NSLog(@"administrativeArea=%@", addressObj.administrativeArea);
            NSLog(@"postalCode=%@", addressObj.postalCode);
            NSLog(@"country=%@", addressObj.country);
            NSLog(@"lines=%@", addressObj.lines);
        }else{
            NSLog(@"地理反編碼錯誤");
        }
    }];
}
//選擇了位置后的回調(diào)方法
- (void)viewController:(GMSAutocompleteViewController*)viewController didAutocompleteWithPlace:(GMSPlace*)place {
    //移動地圖中心到選擇的位置
    _mapView.camera = [GMSCameraPosition cameraWithTarget:place.coordinate zoom:15];
    [viewController dismissViewControllerAnimated:YES completion:nil];
}
//失敗回調(diào)
- (void)viewController:(GMSAutocompleteViewController *)viewController
didFailAutocompleteWithError:(NSError *)error {
    [viewController dismissViewControllerAnimated:YES completion:nil];
}
//取消回調(diào)
- (void)wasCancelled:(GMSAutocompleteViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:nil];
}
//-(void)addMarkers{
//    NSArray * latArr = @[@(_coordinate2D.latitude +0.004),@(_coordinate2D.latitude +0.008),@(_coordinate2D.latitude +0.007),@(_coordinate2D.latitude -0.0022),@(_coordinate2D.latitude -0.004)];
//    NSArray * lngArr = @[@(_coordinate2D.longitude+0.007),@(_coordinate2D.longitude+0.001),@(_coordinate2D.longitude+0.003),@(_coordinate2D.longitude+0.003),@(_coordinate2D.longitude-0.008)];
//    for(int i =0;i < latArr.count; i++){
//        GMSMarker *sydneyMarker = [[GMSMarker alloc]init];
//        sydneyMarker.title=@"Sydney!";
//        sydneyMarker.icon= [UIImage imageNamed:@"marker"];
//        sydneyMarker.position=CLLocationCoordinate2DMake([latArr[i]doubleValue], [lngArr[i]doubleValue]);
//        sydneyMarker.map=_mapView;
//    }
//}
// 獲取當(dāng)前位置權(quán)限提示圖
- (void)locationPermissionAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"位置訪問權(quán)限" message:@"請打開位置訪問權(quán)限,以便于定位您的位置,添加地址信息" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"去設(shè)置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url];
        }
    }];
    [alert addAction:cancle];
    [alert addAction:confirm];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)dealloc{
    [SVProgressHUD dismiss];
    [_locationManager stopUpdatingLocation];
    _mapView = nil;
}

效果如圖


地圖展示

POI檢索
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末械拍,一起剝皮案震驚了整個濱河市突勇,隨后出現(xiàn)的幾起案子射沟,更是在濱河造成了極大的恐慌,老刑警劉巖与境,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異猖吴,居然都是意外死亡摔刁,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進店門海蔽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來共屈,“玉大人,你說我怎么就攤上這事党窜∞忠” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵幌衣,是天一觀的道長矾削。 經(jīng)常有香客問我,道長豁护,這世上最難降的妖魔是什么哼凯? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮楚里,結(jié)果婚禮上断部,老公的妹妹穿的比我還像新娘。我一直安慰自己班缎,他們只是感情好蝴光,可當(dāng)我...
    茶點故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著达址,像睡著了一般蔑祟。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上沉唠,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天做瞪,我揣著相機與錄音,去河邊找鬼右冻。 笑死装蓬,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的纱扭。 我是一名探鬼主播牍帚,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼乳蛾!你這毒婦竟也來了暗赶?” 一聲冷哼從身側(cè)響起鄙币,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蹂随,沒想到半個月后十嘿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡岳锁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年绩衷,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片激率。...
    茶點故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡咳燕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出乒躺,到底是詐尸還是另有隱情招盲,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布嘉冒,位于F島的核電站曹货,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏讳推。R本人自食惡果不足惜控乾,卻給世界環(huán)境...
    茶點故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望娜遵。 院中可真熱鬧蜕衡,春花似錦、人聲如沸设拟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽纳胧。三九已至镰吆,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間跑慕,已是汗流浹背万皿。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留核行,地道東北人牢硅。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像芝雪,于是被迫代替她去往敵國和親减余。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,779評論 2 354

推薦閱讀更多精彩內(nèi)容