簡體   English   中英

iOS - 在應用啟動時縮放到當前用戶位置

[英]iOS - Zoom to the current user location at app start up

我想在啟動時將地圖縮放到當前用戶位置。 我試圖在viewDidLoad中使用mapView.userLocation.coordinate來檢索用戶位置,但返回的坐標是(0,0),可能是因為MapKit在啟動時沒有“找到”用戶位置。

我找到了一個實現方法didUpdateToLocation的解決方案。 我做了以下事情:

- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if ( hasZoomedAtStartUp == NO )
    {
        [self zoomAtStartUp]; // my method to zoom the map
        hasZoomedAtStartUp = YES;
    }
}

我在.h文件中創建的hasZoomedAtStartUp變量,並在ViewDidLoad中用NO初始化它。

這個解決方案工作正常,但我想知道是否有另一種方法可以做到這一點,沒有if語句。 這個IF對於startUp是相關的,所以我想刪除它,出於性能原因。

我非常懷疑一個失敗的if語句是你需要擔心的性能。

您是否經常需要定位服務? 如果沒有,當您不再需要更新位置時,調用stopUpdatingLocation可能會獲得更大的收益。 隨后,您甚至無法訪問didUpdateToLocation,因為您不再獲取新的位置數據。

您現在使用的方法, -locationManager:didUpdateToLocation:fromLocation是對用戶位置執行任何操作的最佳位置。 不過,我會做一些與你不同的事情。

首先,您接受第一個位置更新是最好的。 您可能已經要求一定的准確性,但要求它並不意味着該方法的newLocation是最好的。 通常情況下,從過去的某個時間開始,您將獲得非常低的准確度或緩存位置。 我要做的是檢查新位置的年齡和准確性,並且只有在它放大的時候才能進行。

我要做的另一件事是關閉位置更新,無論是在准確更新時,還是在更新開始后30秒。 設置一個計時器將其關閉,當您將其關閉時,設置一個較長的計時器將其重新打開並再次檢查。

最后,確保您已正確實現-locationManager:didFailWithError:適用於所有情況。 它總是在您提交應用程序時測試的內容之一。 如果它沒有正常失敗(例如,在飛行模式下),它可能會被拒絕。

搜索Stack Overflow以獲取執行這些操作的技術和代碼。

您可以隨時初始化並開始獲取位置更新。 每當收到新位置時,CLLocationManager都會通知您的代理,並將該位置設置為要顯示的地圖區域

//Don't Forget To Adopt CLLocationManagerDelegate  protocol
//set up the Location manager     
locationManager = [[CLLocationManager alloc] init]; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
locationManager.distanceFilter = DISTANCE_FILTER_VALUE;
locationManager.delegate = self; 
[locationManager startUpdatingLocation]

//WIll help to get CurrentLocation implement the CLLocationManager  delegate
 - (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation  *)newLocation fromLocation:(CLLocation *)oldLocation
{
// use this newLocation .coordinate.latitude
}

// set Span
MKCoordinateSpan span; 
//You can set span for how much Zoom to be display like below
span.latitudeDelta=.005;
span.longitudeDelta=.005;

//set Region to be display on MKMapView
MKCoordinateRegion cordinateRegion;
cordinateRegion.center=latAndLongLocation.coordinate;
//latAndLongLocation coordinates should be your current location to be display 
cordinateRegion.span=span;
//set That Region mapView 
[mapView setRegion:cordinateRegion animated:YES];

您可以創建一個“初始”委托實現,可以在縮放到位置后取消注冊,並注冊現在不需要整個縮放的“普通”委托,如果有的話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM