前言
最近在開發(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
如果要查看谷歌地圖的開發(fā)文檔或者APP測試谷歌地圖遗座,都需要翻墻舀凛。
免費的可以使試試 佛跳墻 ,網(wǎng)速也還可以途蒋。
收費的 同學(xué)給推薦了一個socketpro猛遍,買了一個月,19元号坡,網(wǎng)速還可以懊烤。申請賬號流程此處省略。
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檢索