一、pod下载谷歌地图SDK
pod 'GoogleMaps'
pod 'GooglePlaces'
二、初始化谷歌地图
代理 <GMSMapViewDelegate, GMSAutocompleteViewControllerDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;//地图定位对象
@property (nonatomic,strong) GMSMapView *mapView;//地图
@property (nonatomic,strong) GMSMarker *marker;//大头针
//初始化地图
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[_latitude floatValue] longitude:[_longitude floatValue] zoom:12];
self.mapView= [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.mapView.delegate = self; //注册代理属性
self.mapView.settings.compassButton = YES;//显示指南针
self.mapView.frame =self.view.frame;
[self.view addSubview:self.mapView];
if (self.locationManager == nil) {
self.locationManager= [[CLLocationManager alloc]init];
}
self.locationManager.delegate = self;
[self.locationManager requestAlwaysAuthorization];//授权方式,如果在后台也需要定位,那就选择 requestAlwaysAuthorization。
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//最精确的定位
self.locationManager.distanceFilter = kCLDistanceFilterNone; // 默认是kCLDistanceFilterNone,也可以设置其他值,表示用户移动的距离小于该范围内就不会接收到通知
[self.locationManager startUpdatingLocation];
#pragma mark - GMSMapViewDelegate
//移动地图位置,重新定位
- (void)mapView:(GMSMapView*)mapViewdidTapAtCoordinate:(CLLocationCoordinate2D)coordinate{
[self showLocation:coordinate];
}
//根据经纬度显示地图位置和大头针
-(void)showLocation:(CLLocationCoordinate2D)coordinate{
__weak typeof(self) weakSelf =self;
_currentCurCoordinate2D = coordinate;
//地图显示在经纬度位置
GMSCameraPosition*camera = [GMSCameraPosition cameraWithLatitude:coordinate.latitude longitude:coordinate.longitude zoom:14];
self.mapView.camera= camera;
//大头针显示经纬度位置 点击一次先清除上一次的大头针
[self.marker.mapclear];
self.marker.map=nil;
self.marker= [GMSMarkermarkerWithPosition:coordinate];
self.marker.map = self.mapView;
三、搜索地址
GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
acController.delegate=self;
[selfpresentViewController:acController animated:YES completion:nil];
#pragma mark - GMSAutocompleteViewControllerDelegate
// 用户选择搜索中的某个地址后返回的结果回调方法
- (void)viewController:(GMSAutocompleteViewController *)viewController
didAutocompleteWithPlace:(GMSPlace *)place {
[self dismissViewControllerAnimated:YES completion:nil];
[self.marker.map clear];
self.marker.map=nil;
// 通过location 或得到当前位置的经纬度
GMSCameraPosition*camera = [GMSCameraPosition cameraWithLatitude:place.coordinate.latitude longitude:place.coordinate.longitude zoom:14];
CLLocationCoordinate2D position2D =CLLocationCoordinate2DMake (place.coordinate.latitude, place.coordinate.longitude);
self.marker= [GMSMarker markerWithPosition:position2D];
self.mapView.camera= camera;
self.marker.map = self.mapView;
_currentCurCoordinate2D = position2D;
self.addressLb.text= [NSString stringWithFormat:@"%@",place.name];
}