iOS之集成谷歌地图GoogleMap地图选址(定位、搜索)功能

前言

最近在开发一款国外的APP中,需要用到谷歌地图,记录下流程。

1.申请谷歌账号、创建应用、获取API key
2.项目导入SDK
3.配置plist
4.调用代理方法实现需求

一、申请谷歌账号、创建应用、获取API key

谷歌地图开放平台地址:https://cloud.google.com/maps-platform/?hl=zh-CN

  1. 如果要查看谷歌地图的开发文档或者APP测试谷歌地图,都需要翻墙。
    免费的可以使试试 佛跳墙 ,网速也还可以。
    收费的 同学给推荐了一个socketpro,买了一个月,19元,网速还可以。

  2. 申请账号流程此处省略。

3.创建项目,创建完项目 切换到该项目下,创建凭证 获取apikey, 配置api, 配置的时候 选择了2个api,Maps SDK for iOS是用来显示地图和定位,Places API 是用来POI检索用的。

创建项目

创建凭证1

创建凭证2

获取APIkey

配置API

二、项目导入SDK

用的是cocopod 方式集成的,手动的 可以去官方文档查看。

#谷歌地图
pod'GoogleMaps'
pod'GooglePlaces'
  • GoogleMaps:显示基本的定位功能;
  • GooglePlaces:实现搜索功能,官方文档叫做地点自动完成;
  • GooglePlacePicker:是实现获取某个POI的的详细信息,比如名字、详细地址、路线等),这个暂时没用到,如果有需要 也导入即可。

三、配置plist

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>App需要获取定位权限来选择您的地址</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App需要获取定位权限来选择您的地址</string>

四、调用代理方法实现需求

1. 导入头文件
#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 主要用来 国内坐标系的转换
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 导航高度
#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];
    
    //设置地图view,这里是随便初始化了一个经纬度,在获取到当前用户位置到时候会直接更新的
    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;//设置定位精度
        _locationManager.distanceFilter = 10;//设置定位频率,每隔多少米定位一次
        [_locationManager startUpdatingLocation];
    } else {
        //定位不能用
        [self locationPermissionAlert];
        [SVProgressHUD dismiss];
    }
}
#pragma mark - 系统自带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;//只定位一次的标记值
        // 获取最新定位
        CLLocation *location = locations.lastObject;
        // 停止定位
        [_locationManager stopUpdatingLocation];
        //如果是国内,就会转化坐标系,如果是国外坐标,则不会转换。
        _coordinate2D = [JZLocationConverter wgs84ToGcj02:location.coordinate];
        //移动地图中心到当前位置
        _mapView.camera = [GMSCameraPosition cameraWithTarget:_coordinate2D zoom:15];

//        self.marker = [GMSMarker markerWithPosition:_coordinate2D];
//        self.marker.map = self.mapView;
        
        [self getPlace:_coordinate2D];
    }
}
-(void)mapViewDidFinishTileRendering:(GMSMapView *)mapView{
   
}
//地图移动后的代理方法,我这里的需求是地图移动需要刷新网络请求,查找附近的店铺
-(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(@"地理反编码错误");
        }
    }];
}
//选择了位置后的回调方法
- (void)viewController:(GMSAutocompleteViewController*)viewController didAutocompleteWithPlace:(GMSPlace*)place {
    //移动地图中心到选择的位置
    _mapView.camera = [GMSCameraPosition cameraWithTarget:place.coordinate zoom:15];
    [viewController dismissViewControllerAnimated:YES completion:nil];
}
//失败回调
- (void)viewController:(GMSAutocompleteViewController *)viewController
didFailAutocompleteWithError:(NSError *)error {
    [viewController dismissViewControllerAnimated:YES completion:nil];
}
//取消回调
- (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;
//    }
//}
// 获取当前位置权限提示图
- (void)locationPermissionAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"位置访问权限" message:@"请打开位置访问权限,以便于定位您的位置,添加地址信息" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"去设置" 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检索
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容