详解iOS集成GoogleMap(定位、搜索)

2020-01-21 04:32:06于丽

回调2:这里也是点击地图上的某个点API返回的代理方法


- (void)mapView:(GMSMapView *)mapView
didTapPOIWithPlaceID:(NSString *)placeID
   name:(NSString *)name
  location:(CLLocationCoordinate2D)location{
}

tips:值得注意的,两者的区别是:第二个点击代理方法是当你点击POI的时候才会回调,会返回place的name、ID、经纬度;第一个代理方法是只要点击地图任意一个位置就会回调,只会返回经纬度。也就是:每一次的点击,只会执行其中一个代理方法。

搜索:

搜索功能在官方文档是叫做“自动完成”,即你输入一部分的文本,GoogleMap会根据你的文本预测出地点并自动填充返回,具体请看官方文档自动完成

效果如图:

iOS,GoogleMap,定位,搜索

这里你需要做的步骤跟做“定位”的一样:

(1)获取APIKEY

(2) 在application:didFinishLaunchingWithOptions: 注册密匙

1[GMSPlacesClient provideAPIKey:@"YOUR_API_KEY"];

(3) 创建搜索UI并调用代理方法获取API自动填充的结果数组集

小坑提示: GMSPlacesClient跟GMSServices的密匙是不一样的,密匙不对的话,会出现反复调用

viewController:didFailAutocompleteWithError:的现象。

tips:搭建搜索UI又几种方式:1)搜索框直接创建在导航栏 2)搜索栏创建在视图顶部 3)自定义。根据你的需求用代码~

(一)这里是第一种方式(搜索框直接创建在导航栏):


GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
 acController.delegate = self;
 [self presentViewController:acController animated:YES completion:nil];

tips:这里就可以直接往搜索框编辑文字,API会直接给你返回搜索结果集合

(二)调用API代理方法:


// Handle the user's selection. 这是用户选择搜索中的某个地址后返回的结果回调方法
- (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:Level];
 CLLocationCoordinate2D position2D = CLLocationCoordinate2DMake(place.coordinate.latitude,place.coordinate.longitude);
 self.marker = [GMSMarker markerWithPosition:position2D];
 self.mapView.camera = camera;
 self.marker.map = self.mapView;
  
 self.locationLabel.text = place.name;
 self.locationDetailLabel.text = place.formattedAddress;
  
}