2010-03-14 55 views
10

我正在使用MapKit來顯示用戶相對於它們周圍的引腳的位置。我希望能夠通過屏幕左下角的十字準線按鈕來模擬地圖提供的功能。我已經知道MapKit通過MKUserLocation提供了一個CLLocation對象以及用戶的位置,我只是想尋求關於我應該如何關注該位置的建議。我最初的傾向是使用NSTimer每500ms左右在該座標上對地圖進行居中。如何使用MapKit關注用戶位置

有沒有更好的方法來做到這一點?有沒有內置到MapKit,我錯過了將實現這一點?

非常感謝, 布倫丹

回答

7

我認爲我會實際使用CoreLocation CLLocationManager,並使用其委託方法locationManager:didUpdateToLocation:fromLocation:

這樣,您沒有NSTimer的開銷,並且只有在有新的可用位置時纔會更新。

您可以從發送到locationManager:didUpdateToLocation:fromLocation:方法的CLLocation對象中拉取經度和緯度,並將其傳遞到地圖視圖。

+0

雖然MapKit已經在使用GPS了,但最終會不會有這麼大的幫助?我認爲GPS會比定時器使用更多的功率。這是說有一個很好的機會,我錯了。我只在iphone上編了一個星期。 – bloudermilk 2010-03-14 04:30:51

+0

所以你說核心位置**不使用GPS? – 2010-03-14 04:33:37

+0

我在說CL *確實*使用GPS。因此,如果兩個類對GPS接收器(MapKit的藍色用戶位置引腳的內部CLLocationManager以及您提議的CLLocationManager)進行了ping操作,那麼它可能比一個內部MapKit CLLocationManager和一個簡單的NSTimer使用更多的功率。我想這歸結爲iPhone SDK是否足夠智能以支持多個CLLocationManagers而不需要直接附加到GPS。或者,也許MapKit委託提供它自己的didUpdateToLocation:? – bloudermilk 2010-03-14 04:54:02

0

我和Jacob Relkin的答案一致。 This教程提供了在iPhone應用程序中使用CoreLocation的分步過程。希望這可以幫助你。

所有最好的。

+0

@戰士,謝謝:) – 2010-03-14 05:21:03

12

讓地圖自動更新用戶位置就像google地圖一樣簡單。只需將顯示用戶位置設置爲YES

self.mapView.showsUserLocation = YES 

...然後實現MKMapViewDelegate以在位置更新時重新居中地圖。

-(void)    mapView:(MKMapView *)mapView 
     didUpdateUserLocation:(MKUserLocation *)userLocation 
{ 
    if(isTracking) 
    { 
     pendingRegionChange = YES; 
     [self.mapView setCenterCoordinate: userLocation.location.coordinate 
           animated: YES]; 
    } 
} 

,並允許用戶放大&鍋不偷視圖返回到當前位置...

-(void) mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated 
{ 
    if(isTracking && ! pendingRegionChange) 
    { 
     isTracking = NO; 
     [trackingButton setImage: [UIImage imageNamed: @"Location.png"] 
         forState: UIControlStateNormal]; 
    } 

    pendingRegionChange = NO; 
} 

-(IBAction) trackingPressed 
{ 
    pendingRegionChange = YES; 
    isTracking = YES; 
    [mapView setCenterCoordinate: mapView.userLocation.coordinate 
         animated: YES]; 

    [trackingButton setImage: [UIImage imageNamed: @"Location-Tracking.png"] 
        forState: UIControlStateNormal]; 
} 
+0

使用MKMApView的中心比CoreLocation的用戶位置更好嗎?我確實有一個LocationUpdater類,它在更新時返回一個新的CLLocation。 MKMapView是否以相同頻率更新? – quantumpotato 2011-01-30 01:46:30

39

如果你在IOS5 +,這是很容易的。只需使用以下代碼更改「userTrackingMode」:

[_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES]; 

這將順利地跟隨用戶當前位置。如果拖動地圖,它甚至會將跟蹤模式設置回MKUserTrackingModeNone,這通常是您想要的行爲。

+7

接受答案概念的明顯侷限性的另一個證明。這是最好的答案!雅各布的回答在四年前很棒,但現在已經完全過時了,但它會永遠保持第一個答案。 – KPM 2014-09-30 13:02:22

相關問題