1

我的应用程序中的地图视图出现问题。我创建了一个按钮,单击该按钮应在地图上显示用户位置,但没有任何反应(没有出现错误消息)。

我相信问题可能在于我写代表的方式。相关 .h 和 .m 文件的代码如下:

地图视图控制器.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

地图视图控制器.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

任何帮助将不胜感激,谢谢

4

1 回答 1

0

您必须实现 MapKit 代表。.h(确保在视图控制器中添加委托签名)

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

额外:处理应用程序是否在前台:

我们添加 2 个事件观察者来观察 App 正在进入后台/返回活动状态:

- (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];
}
于 2015-01-19T02:16:10.380 回答