我在RootViewController.m上有一个标签。标签有2个按钮。点击后的第一个按钮将转到CorpViewcontroller,它上面有mapView。当我在第一次尝试时单击第一个按钮时,地图为空白,底部带有谷歌标签。我必须再次单击然后再次单击该按钮,然后显示地图。是否可以始终在第一个按钮单击时显示地图?
我的rootViewController.m转到第二个屏幕:
[self.navigationController pushViewController:self.corpController animated:YES];
名为corpViewController的第二个屏幕具有以下代码:
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"Set Remote Location";
self.jsonData = [[NSMutableData alloc] init];
mapView.showsUserLocation = YES;
//Setup the double tap gesture for getting the remote location..
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(handleGesture:)];
tgr.numberOfTapsRequired = 2;
tgr.numberOfTouchesRequired = 1;
[mapView addGestureRecognizer:tgr];
mapView.delegate = self;
NSLog(@"viewDidLoad done");
}
- (void)viewWillAppear:(BOOL)animated {
NSLog(@"viewWillAppear");
appDelegate = (NBSAppDelegate *)[[UIApplication sharedApplication] delegate];
double curLat = [appDelegate.curLat doubleValue];
MKUserLocation *userLocation = mapView.userLocation;
double miles = 10.0;
double scalingFactor = ABS( (cos(2 * M_PI * curLat / 360.0) ));
MKCoordinateSpan span;
span.latitudeDelta = miles/69.0;
span.longitudeDelta = miles/(scalingFactor * 69.0);
MKCoordinateRegion region2;
region2.span = span;
region2.center = userLocation.coordinate;
[mapView setRegion:region2 animated:YES];
NSLog(@"viewWillAppear done..");
}
请告知。
谢谢
答案 0 :(得分:3)
您是否正在视图控制器的viewDidLoad
方法中初始化MapView?
如果是这样,请尝试将其移至viewDidAppear
方法。这对我有用。
答案 1 :(得分:2)
在viewDidLoad
showsUserLocation
设置YES
到viewWillAppear
,mapView.userLocation
,您正在缩放userLocation
坐标。
将showsUserLocation
设置为YES
后,viewWillAppear
属性通常不会立即使用有效坐标。
第一次显示视图控制器时,它仍然无效,您正在缩放到坐标0,0。
当您第二次显示视图控制器时,已获取用户位置且坐标有效。
不要放大mapView:didUpdateUserLocation:
中的用户位置,而是在地图视图获取用户位置更新时调用的委托方法mapView.showsUserLocation = YES;
中执行此操作。
此外,您还可能希望将viewWillAppear
移至viewWillDisappear
,然后移至NO
,将其设置为MKCoordinateRegionMakeWithDistance
。这样,每次显示视图控制器时,地图视图都会放大到用户位置,而不是第一次。
一个不相关的观点是,要放大到特定距离,使用corpViewController
函数会更容易,而不是尝试将里程转换为度数。
以下是- (void)viewWillAppear:(BOOL)animated
{
//move this from viewDidLoad to here...
mapView.showsUserLocation = YES;
}
-(void)viewWillDisappear:(BOOL)animated
{
mapView.showsUserLocation = NO;
}
-(void)mapView:(MKMapView *)mv didUpdateUserLocation:(MKUserLocation *)userLocation
//Changed the **internal** parameter name from mapView to mv
//to avoid a compiler warning about it hiding instance var with same name.
//It's better to use the passed parameter variable anyway.
{
NSLog(@"didUpdateUserLocation");
double miles = 10.0;
//Instead of manually calculating span from miles to degrees,
//use MKCoordinateRegionMakeWithDistance function...
//Just need to convert miles to meters.
CLLocationDistance meters = miles * 1609.344;
MKCoordinateRegion region2 = MKCoordinateRegionMakeWithDistance
(userLocation.coordinate, meters, meters);
[mv setRegion:region2 animated:YES];
}
中建议的更改示例:
{{1}}