如何使用MapKit关注用户位置

时间:2010-03-14 01:09:09

标签: iphone cocoa-touch mapkit

我正在使用MapKit显示用户相对于它们周围的引脚的位置。我希望能够通过屏幕左下角的十字准线按钮模仿地图提供的功能。我已经知道MapKit通过MKUserLocation提供了一个CLLocation对象和用户的位置,我只是想就如何关注​​该位置寻求建议。我最初的倾向是使用NSTimer将地图集中在每500ms左右的坐标上。

有更好的方法吗?是否有一些内置于MapKit中的内容可以实现这一点?

非常感谢, 布伦丹

4 个答案:

答案 0 :(得分:39)

如果您使用的是IOS5 +,这非常简单。只需使用以下代码更改“userTrackingMode”:

[_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];

这将顺利跟随用户当前位置。如果您拖动地图,它甚至会将跟踪模式设置回MKUserTrackingModeNone,这通常是您想要的行为。

答案 1 :(得分:12)

让地图像谷歌地图一样自动更新用户位置非常简单。只需将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];
}

答案 2 :(得分:7)

我认为我实际上会使用CoreLocation CLLocationManager并使用其委托方法locationManager:didUpdateToLocation:fromLocation:

这样,您就没有NSTimer的开销,只有在有新位置可用时才会更新。

您可以从发送到CLLocation方法的locationManager:didUpdateToLocation:fromLocation:对象中提取经度和纬度,并将其传递给地图视图。

答案 3 :(得分:0)

我和Jacob Relkin一起回答。 This教程提供了在iPhone应用程序中使用CoreLocation的分步过程。希望这对你有所帮助。

所有最佳。

相关问题