簡體   English   中英

如何使用MapKit關注用戶位置

[英]How to follow user location with MapKit

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

有一個更好的方法嗎? 是否有一些內置於MapKit中的東西,我將失蹤,這將實現這一目標?

非常感謝,布蘭登

如果您使用的是IOS5 +,這非常簡單。 只需使用以下代碼更改“userTrackingMode”:

[_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];

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

讓地圖像谷歌地圖一樣自動更新用戶位置非常簡單。 只需將showsUserLocation設置為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];
}

我認為我實際上會使用CoreLocation CLLocationManager並使用其委托方法locationManager:didUpdateToLocation:fromLocation: .

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

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

我和Jacob Relkin一起回答。 教程提供了在iPhone應用程序中使用CoreLocation的分步過程。 希望這對你有所幫助。

祝一切順利。

暫無
暫無

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

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