如何在GMSMapView中获取用户点击位置的经纬度?是否需启用GooglePlacePickerViewController?
不需要用GooglePlacePickerViewController,直接在GMSMapView上就能搞定!
嘿,其实完全没必要折腾GooglePlacePickerViewController——你的需求(在显示当前位置的GMSMapView上获取点击位置的经纬度)用GMSMapView自带的功能就能轻松实现,而且流程更顺畅,不需要跳转到新的页面。
下面是具体的实现方式:
方法一:利用GMSMapView的代理回调(最推荐)
GMSMapView本身提供了专门的代理方法来监听地图上的点击事件,直接就能拿到点击位置的经纬度:
步骤1:让你的ViewController遵守GMSMapViewDelegate协议
// Swift示例 class YourMapViewController: UIViewController, GMSMapViewDelegate { // ... 你的其他代码 }
// Objective-C示例 @interface YourMapViewController () <GMSMapViewDelegate> @end
步骤2:设置GMSMapView的代理
在初始化GMSMapView或者viewDidLoad里,把代理指向当前ViewController:
// Swift override func viewDidLoad() { super.viewDidLoad() let mapView = GMSMapView(frame: view.bounds) mapView.delegate = self // 配置地图显示当前位置的代码(你已经实现的部分) view.addSubview(mapView) }
// Objective-C - (void)viewDidLoad { [super viewDidLoad]; GMSMapView *mapView = [[GMSMapView alloc] initWithFrame:self.view.bounds]; mapView.delegate = self; // 配置地图显示当前位置的代码(你已经实现的部分) [self.view addSubview:mapView]; }
步骤3:实现点击回调方法
这个方法会在用户点击地图的任意位置时触发,直接返回点击点的经纬度坐标:
// Swift func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) { let latitude = coordinate.latitude let longitude = coordinate.longitude print("点击位置的经纬度:\(latitude), \(longitude)") // 在这里处理你拿到的经纬度,比如保存、显示等 }
// Objective-C - (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate { CLLocationDegrees latitude = coordinate.latitude; CLLocationDegrees longitude = coordinate.longitude; NSLog(@"点击位置的经纬度:%f, %f", latitude, longitude); // 在这里处理你拿到的经纬度 }
为什么不用GooglePlacePickerViewController?
GooglePlacePickerViewController的核心作用是让用户选择具体的地点(带名称、地址、POI信息等),如果你的需求只是获取经纬度,用它反而会多一层跳转,增加操作步骤,完全没必要。直接在当前的GMSMapView上处理点击,体验更流畅,代码也更简洁。
额外提示
如果需要在点击后给用户一个确认的交互(比如弹出弹窗问是否确认选择这个位置),可以在didTapAtCoordinate:方法里添加弹窗逻辑,完全不需要依赖外部组件。
内容的提问来源于stack exchange,提问作者sam




