Ios 如何在特定位置居中,然后缩放到当前位置
我是个新手,请原谅我的无知。我花了一些时间试图理解我所缺少的东西,但却无法理解 加载时,我的应用程序以华盛顿州为中心,但当我尝试缩放到用户当前位置时,它将我置于纬度0经度0。如果我注释掉“//startup:center over WA”部分,它将集中在用户当前位置,然后goToLocation可以正常工作 我如何让它以华盛顿州为中心,然后在单击goToLocation时缩放到用户的当前位置 谢谢Ios 如何在特定位置居中,然后缩放到当前位置,ios,mkmapview,mapkit,Ios,Mkmapview,Mapkit,我是个新手,请原谅我的无知。我花了一些时间试图理解我所缺少的东西,但却无法理解 加载时,我的应用程序以华盛顿州为中心,但当我尝试缩放到用户当前位置时,它将我置于纬度0经度0。如果我注释掉“//startup:center over WA”部分,它将集中在用户当前位置,然后goToLocation可以正常工作 我如何让它以华盛顿州为中心,然后在单击goToLocation时缩放到用户的当前位置 谢谢 - (void)viewDidLoad { [super viewDidLoad];
- (void)viewDidLoad {
[super viewDidLoad];
[self loadOurAnnotations];
[mapView setShowsUserLocation:NO];
// startup: center over WA
CLLocationCoordinate2D defaultCoordinate;
defaultCoordinate.latitude = 47.517201;
defaultCoordinate.longitude = -120.366211;
[mapView setRegion:MKCoordinateRegionMake(defaultCoordinate, MKCoordinateSpanMake(6.8, 6.8)) animated:NO];
}
-(IBAction)goToLocation {
MKUserLocation *myLocation = [mapView userLocation];
CLLocationCoordinate2D coord = [[myLocation location] coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 350, 350);
[mapView setRegion:region animated:YES];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView commitAnimations];
}
首先,要在
MKMapView
中使用userLocation
,您必须将YES
传递给setShowsUserLocation
(而不是NO
)
接下来,打开showsUserLocation
后,地图视图可能需要几秒钟或更长时间来确定位置并设置userLocation
。在此之前,位置将为零(坐标为0,0)
要真正了解userLocation何时准备就绪(或更新),请实现didUpdateUserLocation
delegate方法。如果在确定用户位置时出现问题,那么实施didFailToLocateUserWithError
方法也很有帮助
但是,在您的情况下,您可以在goToLocation
方法中执行以下操作:
MKUserLocation *myLocation = [mapView userLocation];
if (myLocation.location == nil)
{
NSLog(@"user location has not been determined yet");
return;
}
CLLocationCoordinate2D coord = [[myLocation location] coordinate];
MKCoordinateRegion region = ... //rest of the code stays the same
顺便说一句,该方法末尾的动画语句没有任何作用。首先,要在
MKMapView
中使用userLocation
,您必须将YES
传递给setShowsUserLocation
(而不是NO
)
接下来,打开showsUserLocation
后,地图视图可能需要几秒钟或更长时间来确定位置并设置userLocation
。在此之前,位置将为零(坐标为0,0)
要真正了解userLocation何时准备就绪(或更新),请实现didUpdateUserLocation
delegate方法。如果在确定用户位置时出现问题,那么实施didFailToLocateUserWithError
方法也很有帮助
但是,在您的情况下,您可以在goToLocation
方法中执行以下操作:
MKUserLocation *myLocation = [mapView userLocation];
if (myLocation.location == nil)
{
NSLog(@"user location has not been determined yet");
return;
}
CLLocationCoordinate2D coord = [[myLocation location] coordinate];
MKCoordinateRegion region = ... //rest of the code stays the same
顺便说一句,该方法末尾的动画语句没有任何作用。非常感谢您的帮助,Anna。我会修修补补的。非常感谢你的帮助,安娜。我将对此进行修补。