ios 定期获取我的位置并设置按钮以获取我的位置 - Google 地图不工作

ios getting my location regularly and setting button to get my location - Google Map not working

我正在开发 Google 地图模块,使用 1.9.0 Bundle,定期查找我的位置,比如说 10 秒,然后创建一个按钮来获取我的位置按钮作为地图视图设置之一

执行时打开位置服务,点击右下角无反应,或没有,位置管理器不工作。我可以显示任何使用定位服务的迹象。

我不确定在设置此地图时缺少什么,因为我严格遵循 SDKDemos - ios google 演示项目来设置我的模块。你能告诉我设置它的确切方法吗?

以下是我的代码:

@implementation MapViewController


-(bool)isNetworkAvailable
{
    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityRef address;
    address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
    Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
    CFRelease(address);

    bool canReach = success
    && !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
    && (flags & kSCNetworkReachabilityFlagsReachable);

    return canReach;
}


- (void)requestAlwaysAuthorization
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled";
        NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];
        [alertView show];
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [locationManager requestAlwaysAuthorization];
    }
}


- (void)viewDidLoad

{
    [super viewDidLoad];

    if([self isNetworkAvailable]){
        NSLog(@"connected ");
    }else {
        NSLog(@"not connected ");
    }

    CarArray = [[NSMutableArray alloc] init];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    float latitide = [defaults floatForKey:@"lati"];
    float longitude = [defaults floatForKey:@"longi"];
    NSString *desp = [defaults objectForKey:@"desp"];


    GMSMarker *marker = [[GMSMarker alloc] init];
    NSLog(@"assadsd arrived map");
    if(latitide!=0.00&&longitude!=0.00) {
        CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude);

        marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude);
        camera = [GMSCameraPosition cameraWithLatitude:latitide  longitude:longitude  zoom:12];
    }else{
        camera = [GMSCameraPosition cameraWithLatitude:22.2855200   longitude:114.1576900  zoom:12];
        marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
    }


    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    marker.snippet = @"HK";

    mapView_.mapType = kGMSTypeSatellite;
    mapView_.delegate = self;

    mapView_.settings.myLocationButton = YES;
    mapView_.settings.compassButton = YES;


    dispatch_async(dispatch_get_main_queue(), ^{
        mapView_.myLocationEnabled = YES;
    });


    if(desp.length > 0 ){
        marker.title = desp;
    }

    // Setup location services
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"Please enable location services");
        return;
    }

    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        NSLog(@"Please authorize location services");
        return;
    }


    locationManager = [[CLLocationManager alloc]init];
    locationManager.delegate = self;


           [locationManager requestWhenInUseAuthorization];



          [locationManager requestAlwaysAuthorization];



    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = 5.0f;


    [mapView_ addObserver:self
                   forKeyPath:@"myLocation"
                      options:(NSKeyValueObservingOptionNew |
                               NSKeyValueObservingOptionOld)
                      context:NULL];


    marker.map = mapView_;



    self.view = mapView_;

    [locationManager startUpdatingLocation];

    GMSCircle *geoFenceCircle = [GMSCircle circleWithPosition:  CLLocationCoordinate2DMake(22.2855200, 114.1576900) radius:1400];
    geoFenceCircle.tappable = true;
    [geoFenceCircle setFillColor:[UIColor colorWithRed:1 green:0 blue:0 alpha:.5]];

    geoFenceCircle.strokeWidth = 13;
    geoFenceCircle.strokeColor = [UIColor orangeColor];
    geoFenceCircle.map = mapView_; // Add it to the map.


    NSLog(@"assadsd configured d map");

}


- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if (!firstLocationUpdate_) {
        // If the first location update has not yet been recieved, then jump to that
        // location.
        firstLocationUpdate_ = YES;
        CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
        mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
                                                         zoom:14];
    }
}


- (void)dealloc {
    [mapView_ removeObserver:self
                  forKeyPath:@"myLocation"
                     context:NULL];
}




-(void)mapView:(GMSMapView *)mapView didDragMarker:(GMSMarker *)marker {
    [mapView clear];

    // Re-draw marker
    marker.map = mapView;

    // Create your circle with the new marker
    GMSCircle *circ = [GMSCircle circleWithPosition:marker.position radius:1000];
    circ.fillColor = [UIColor grayColor];
    circ.strokeColor = [UIColor redColor];
    circ.strokeWidth = 5;
    circ.map = mapView;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex:%ld",(long)buttonIndex);

    if (alertView.tag == 121 && buttonIndex == 1)
    {
        //code for opening settings app in iOS 8
        [[UIApplication sharedApplication] openURL:[NSURL  URLWithString:UIApplicationOpenSettingsURLString]];
    }
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {

    NSLog(@"%@",error.userInfo);
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        NSLog(@"Please authorize location services");
        return;
    }

    NSLog(@"CLLocationManager error: %@", error.localizedFailureReason);
    return;

}

-(void) handleDoubleTap {
    NSLog(@"location double tap ");
}
-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}



// CLLocationDelegate
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations{
    CLLocation *location = [locations lastObject];

    if (markera == nil) {
        markera = [[GMSMarker alloc] init] ;
        markera.position   = CLLocationCoordinate2DMake(22.86, 111.20);
        markera.groundAnchor = CGPointMake(0.5f, 0.97f); // Taking into account walker's shadow
        markera.map = mapView_;

    }else {
        [CATransaction begin];
        [CATransaction setAnimationDuration:2.0];
        markera.position = location.coordinate;
        [CATransaction commit];

    }


        GMSCameraUpdate *move = [GMSCameraUpdate setTarget:location.coordinate zoom:17];
        [mapView_ animateWithCameraUpdate:move];
}

我已经在我的项目

中设置了pinfo.list的以下参数

NSLocationAlwaysUsageDescription -> 需要位置才能确定您所在的位置 NSLocationWhenInUseUsageDescription -> 需要位置才能找出您所在的位置

我的测试设备是8.3,iphone6

你的 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ 接到电话了吗?

如果没有,您需要确保您的 MapViewController 实现了 CLLocationDelegate。 (例如:@interface ViewController : UIViewController<CLLocationManagerDelegate> 在您的 MapViewController.h 文件中)

你可以尝试 this working example from GitHub, or the code snippet 这个要点。

另外,你应该在你的真实设备上测试它,否则你必须在你的 XCode 模拟器中模拟一个位置(见下图,但它可能并不总是有效)。

您必须将 NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription 添加到您的 info.plist 文件(注意:不要重命名或更改 info.plist 文件的扩展名,扩展名必须是 .plist):