获取当前位置iOS,Google Maps API的坐标

我一直在努力改变Google Maps API中相机的价值。 因此,只要您打开应用程序,使用CoreLocation并将这些值传递到相机,它就会显示用户的位置。 网上还有一些其他的教程,但没有任何适合我的东西。

如果你能帮助它,将是大规模的赞赏。

@implementation HMSBViewController{ CLLocationManager *_locationManager; } - (NSString *)deviceLocation { NSString *theLocation = [NSString stringWithFormat:@"latitude: %f longitude: %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude]; return theLocation; } - (void)viewDidLoad { //mapView.settings.myLocationButton = YES; mapView.myLocationEnabled = YES; _locationManager = [[CLLocationManager alloc] init]; _locationManager.distanceFilter = kCLDistanceFilterNone; _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; // Setting the accuracy to the best possible if([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { [_locationManager requestAlwaysAuthorization]; } [_locationManager startUpdatingLocation]; } - (void)loadView{ CLLocation *myLocation = mapView.myLocation; GMSMarker *marker = [[GMSMarker alloc] init]; marker.position = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude); marker.title = @"Current Location"; marker.map = mapView; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:_locationManager.location.coordinate.latitude longitude:_locationManager.location.coordinate.longitude zoom:6]; mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera]; self.view = mapView; NSLog(@"%f, %f", _locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude); } 

当应用程序运行时,坐标始终设置为零。

谢谢

发生这种情况是因为Google Maps API在放置在控制器视图中后才会获取当前位置。 要解决这个限制,你应该创build一个通知,告诉你的控制器当前位置是否可用。

在你的viewWillApper上添加这个观察者:

 [mapView addObserver:self forKeyPath:@"myLocation" options:0 context:nil]; 

然后添加-(void)observeValueForKeyPath:ofObject:change:context:每当keyPath值发生更改时调用。 在这个方法上,你现在可以获得当前的位置,并将地图制作成animation,从而显示在那里。 在方法结束时,您应该注销观察者,因为如果未注销,则每当位置改变时都会调用此方法。

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([keyPath isEqualToString:@"myLocation"]) { CLLocation *location = [object myLocation]; CLLocationCoordinate2D target = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude); [mapView animateToLocation:target]; @try { [map removeObserver:self forKeyPath:@"myLocation"]; } @catch(id exception){ //do nothing, obviously it wasn't attached because an exception was thrown } } } 

地图可能需要一段时间才能获得当前位置,但速度通常很快。