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

NSLocationAlwaysAndWhenInUseUsageDescription
App需要获取定位权限来选择您的地址
NSLocationWhenInUseUsageDescription
App需要获取定位权限来选择您的地址

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

1. 导入头文件
#import 
#import 
#import 
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 
#import 
#import 
#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 ()

@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检索

你可能感兴趣的:(iOS之集成谷歌地图GoogleMap地图选址(定位、搜索)功能)