如何在谷歌地图中显示用户的当前位置?
我必须阅读此表格 GPS 吗?
要移动到当前位置,您必须:
self.googleMapsView.myLocationEnabled = YES;
然后,您可以在 viewWillAppear 方法中设置键值观察器,然后使用 GoogleMaps SDK 的位置管理器获取位置更新。
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Implement here to check if already KVO is implemented.
...
[self.googleMapsView addObserver:self forKeyPath:@"myLocation" options:NSKeyValueObservingNew context: nil]
}
然后观察属性。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"myLocation"] && [object isKindOfClass:[GMSMapView class]])
{
[self.googleMapsView animateToCameraPosition:[GMSCameraPosition cameraWithLatitude:self.googleMapsView.myLocation.coordinate.latitude
longitude:self.googleMapsView.myLocation.coordinate.longitude
zoom:self.googleMapsView.projection.zoom]];
}
}
不要忘记在 viewWillDisappear 中注销您的观察者。
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// Implement here if the view has registered KVO
...
[self.googleMapsView removeObserver:self forKeyPath:@"myLocation"];
}
基于Weindl的回答。
使用 CLLocationManagerDelegate 和 CLLocationManager 获取坐标然后将它们注入 GMSMapView 的最佳方法和最简单的方法:
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithTarget:CLLocationCoordinate2DMake(0, 0) zoom: 10];
mapView = [GMSMapView mapWithFrame:self.viewForMap.bounds camera:camera];
mapView.myLocationEnabled = YES;
[self.viewForMap addSubview:mapView];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations lastObject];
[mapView animateToLocation:currentLocation.coordinate];
}
... NSKeyValueObservingOptionNew
已贬值。
使用,例如:
[self.googleMapsView addObserver:self forKeyPath:@"myLocation" options:NSKeyValueObservingOptionNew context:nil];
//In viewDidLoad
self.mapView.myLocationEnabled = YES;
//Whenever you need to check location
CLLocation *myLocation = self.mapView.myLocation;
NSLog(@"%f %f",myLocation.coordinate.latitude, myLocation.coordinate.longitude);
(void)updateCurrentLocation {
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D currentLocation = [location coordinate];
if(noStartSet){
startPoint = currentLocation;
noStartSet = FALSE;
}
[self.mapView animateToLocation:currentLocation];
}
viewdidload
如果您希望您的当前位置作为默认位置,请在您的中调用此方法。