如何使用MapKit关注用户位置

blo*_*ilk 10 iphone cocoa-touch mapkit

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

有一个更好的方法吗?是否有一些内置于MapKit中的东西,我将失踪,这将实现这一目标?

非常感谢,布兰登

Pet*_*ill 40

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

[_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
Run Code Online (Sandbox Code Playgroud)

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

  • 接受答案概念的明显局限性的另一个证明.这应该是最重要的答案!雅各布的回答在四年前很棒,但现在已经完全过时了,但它将永远显示为第一个答案. (7认同)

Pau*_*der 12

让地图像谷歌地图一样自动更新用户位置非常简单.只需将showsUserLocation设置为YES即可

self.mapView.showsUserLocation = YES
Run Code Online (Sandbox Code Playgroud)

...然后实现MKMapViewDelegate,以便在更新位置时重新定位地图.

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

并允许用户缩放和平移而不会将视图窃回当前位置...

-(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];
}
Run Code Online (Sandbox Code Playgroud)


Jac*_*kin 7

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

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

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