iOS map 标记和当前位置未显示

标签 ios objective-c mapkit cllocationmanager location-services

我有一个导入 SWRevealViewController 的 MapViewController,老实说我没有在下面编写这行代码。我尝试运行该应用程序,但不幸的是, map 没有显示当前位置,甚至定位服务也无法打开手机,即使该应用程序被授予访问 GPS 的权限。由于我不是 iOS 开发的期望者,所以我需要有人查看代码并解释此代码中缺少的内容。我看过类似的问题,但即使对于学习 Objective-C 的人来说,它们似乎也很简单。我认为此代码的问题是此处导入的 SWRevealViewController,我认为它是一个库或我不知道的东西。

#import "MapViewController.h"
#import "SWRevealViewController.h"

// New York
#define NY_LATITUDE 40.754445
#define NY_LONGITUDE -73.977364

// Span and distance
#define SPAN_VALUE 1.0f
#define DISTANCE 500



@interface MapViewController ()
- (void)startLocationServices;
- (void)stopLocationServices;
@end

@implementation MapViewController

@synthesize locationManager;
@synthesize gpsDisplay;
@synthesize mapk;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)sendRequest:(id)sender {
        [self alertStatus:@"An assistance request has been sent, you will be contacted shortly." :@"Send assistance request" :0];
    [self performSegueWithIdentifier:@"sendRequest" sender:nil];
    
}

- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    alertView.tag = tag;
    [alertView show];
}
-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:    (NSInteger)buttonIndex
{
    if(buttonIndex==0)
    {
        //NSLog(@"OK Clicked");
        //  [self alertStatus:@"An assistance request has been sent, you will be contacted shortly. " :@"I just had an accident" :0];
       // [self performSegueWithIdentifier:@"checkProgress" sender:nil];
        
        
    }}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self startLocationServices];
    
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager startUpdatingLocation];
    } else {
        NSLog(@"Location services are not enabled");
    }
    
    // Set a timer to stop the Location services
    //[NSTimer scheduledTimerWithTimeInterval:100.0 target:self selector:@selector(stopLocationServices) userInfo:nil repeats:NO];
    
    _sidebarButton.tintColor = [UIColor colorWithWhite:0.1f alpha:0.9f];
    
    // Set the side bar button action. When it's tapped, it'll show up the sidebar.
    _sidebarButton.target = self.revealViewController;
    _sidebarButton.action = @selector(revealToggle:);
    
    // Set the gesture
    [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
//    CLLocationManager *cllocationManager = [[CLLocationManager alloc] init];
//    cllocationManager.delegate = self;
//    cllocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
//    cllocationManager.distanceFilter = 20.0f;
//    
//    if ([CLLocationManager locationServicesEnabled])
//    {
//        [cllocationManager startUpdatingLocation];
//    }
//    else
//    {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Turn On Location Services to find your location"
//                                                        message:nil delegate:nil
//                                              cancelButtonTitle:@"OK"
//                                              otherButtonTitles:nil];
//        [alert show];
//        // [alert release];
//    }
}




- (IBAction)mapChanger:(id)sender {
    
    switch (((UISegmentedControl *) sender).selectedSegmentIndex) {
        case 0:
            self.mapk.mapType = MKMapTypeStandard;
            break;
        case 1:
            self.mapk.mapType = MKMapTypeSatellite;
            break;
        case 2:
            self.mapk.mapType = MKMapTypeHybrid;
            break;
            
        default:
            break;
    }
}

- (void)startLocationServices
{
    // create the Location Manager
    if (self.locationManager == nil) {
        self.locationManager = [CLLocationManager new];
    }
    
    // settings
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
    
    // start services
    [self.locationManager startUpdatingLocation];
    self.gpsDisplay.text = @"Location Service started.";
}

- (void)stopLocationServices
{
    // stop services
    [self.locationManager stopUpdatingLocation];
    [self.locationManager setDelegate:nil];
    self.gpsDisplay.text = @"Location Services stopped.";
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    CLLocationCoordinate2D loc = [userLocation coordinate];
    // CLLocationDistance in meters (1 meter = 3.3 feet)
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, DISTANCE, DISTANCE);
    [mapView setRegion:region animated:YES];
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    NSString *coords =@"lat";
    coords = [coords stringByAppendingString:[NSString stringWithFormat:@"%f", newLocation.coordinate.latitude]];
    coords = [coords stringByAppendingString:@"lon"];
    coords = [coords stringByAppendingString:[NSString stringWithFormat:@"%f", newLocation.coordinate.longitude]];
    
    self.gpsDisplay.text = coords;
    
    MKCoordinateRegion region;
    region.center.latitude = newLocation.coordinate.latitude;
    region.center.longitude = newLocation.coordinate.longitude;
    region.span.latitudeDelta = SPAN_VALUE;
    region.span.longitudeDelta = SPAN_VALUE;
    [self.mapk setRegion:region animated:YES];
    
}

- (void)viewDidUnload {
    //[self setUpdates:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

最佳答案

除了前面的答案,请注意您必须指定访问用户位置信息的原因,将相对键(NSLocationAlwaysUsageDescription 或 NSLocationWhenInUseUsageDescription)添加到项目的 Info.plist

例如:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is required to find out jobs around you are</string>

关于iOS map 标记和当前位置未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27340611/

相关文章:

ios - 用户卸载 iPhone 应用程序时的通知

ios - 如何覆盖 NSManagedObjects 的 hash 和 isEqual?

ios - 如何解决 CALayer 异常?

ios - 如何根据 iOS 中的文本长度更改 UILabel 宽度?

ios - Swift 3 - MapKit 注释触摸监听器

iphone - 以编程方式确定 iPhone 是否越狱

ios - 后台播种/加载 iOS 核心数据存储

ios - 当我启用使用自动布局时 Xcode 5 崩溃

objective-c - 在 map 上的给定点之间绘制折线

ios - 如何实现 Realtor iPad 应用程序中使用的自定义绘图搜索工具?