[英]How do I center over a specific location and then zoom to current location
这里有很多新手,请原谅。 我花了一些时间试图了解我所缺少的东西,但无法弄清楚。
加载时,我的应用程序以华盛顿州为中心,但是当我尝试缩放到用户当前位置时,它的纬度为0经度0。如果我注释掉“ // startup:center over WA”部分,则它将以用户当前位置为中心然后goToLocation可以正常工作。
如何单击goToLocation使其位于华盛顿州的中心,然后缩放到用户当前位置?
谢谢!
- (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
委托方法。 如果确定用户位置有问题,则实现didFailToLocateUserWithError
方法也很有帮助。
但是,根据您的情况,您可以在goToLocation
方法中执行以下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
顺便说一句,该方法末尾的动画语句不执行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.