[英]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.