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



我一直在努力更改Google Maps API中的相机值。这样一旦打开应用程序,使用corelogation并将这些值传递到相机中,它就会显示用户位置。在线还有其他一些教程,但对我没有任何作用。

如果您能提供帮助,将不胜感激。

@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映射API仅在将其放置在控制器视图上后获取当前位置。要解决此限制,您应该创建一个通知,该通知告诉您的控制器当前位置可用时。

在您的ViewWillApper上添加此观察者:

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

然后添加每次keyPath值更改时称为-(void)observeValueForKeyPath:ofObject:change:context:。在此方法上,您现在可以获取当前位置并将地图对其进行动画,以便它显示为中心。在方法的末尾,您应该检查观察者,因为如果未扫描该方法,则每次位置更改时都会调用此方法。

- (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
        }
    }
}

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

最新更新