showsUserLocation action attached to button not wo

2019-08-05 22:41发布

问题:

I am having problems with a map view in my app. I have created a button that when clicked should show users location on the map, but nothing happens (no error messages occur).

I believe the issue may lie in the way I've written the delegates. The code from the relevant .h and .m files is below:

mapViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface mapViewController : UIViewController  {
MKMapView *mapview;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapview;
-(IBAction)setMap:(id)sender;
-(IBAction)getCurrentLocation:(id)sender;
@property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
@end

mapViewController.m

#import "mapViewController.h"
@interface mapViewController ()
@end
@implementation mapViewController {
CLLocationManager *locationManager;
}
@synthesize mapview;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.requestWhenInUseAuthorization;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)setMap:(id)sender {
switch (((UISegmentedControl *) sender).selectedSegmentIndex) {
case 0:
    mapview.mapType = MKMapTypeStandard;
    break;
case 1:
    mapview.mapType = MKMapTypeSatellite;
    break;
case 2:
    mapview.mapType = MKMapTypeHybrid;
    break;
   default:
    break;
}
}
-(IBAction)getCurrentLocation:(id)sender {
mapview.showsUserLocation = YES;
}
@end

Any help would be greatly appreciated, thanks

回答1:

You have to implement the MapKit delegates. (Make sure you add the delegate signature in .h of your view controller)

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    CLLocationCoordinate2D location;
    location.latitude = userLocation.coordinate.latitude;
    location.longitude = userLocation.coordinate.longitude;
    region.span = span;
    region.center = location;
    [mapView setRegion:region animated:YES];
 }

Extra: To handle App is on foreground or not:

We add 2 event observers to observe the App is entering background / returning active:

- (void)viewDidLoad{
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appToBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appReturnsActive) name:UIApplicationDidBecomeActiveNotification object:nil];
} 

- (void)appToBackground{
  [mapview setShowsUserLocation:NO];
}

- (void)appReturnsActive{
  [mapview setShowsUserLocation:YES];
}