【问题标题】:How do I center over a specific location and then zoom to current location如何以特定位置为中心然后缩放到当前位置
【发布时间】:2011-09-02 22:33:07
【问题描述】:

这里是新手,请原谅我的无知。我花了一些时间试图了解我错过了什么,但无法弄清楚。

我的应用程序在加载时以华盛顿州为中心,但当我尝试缩放到用户当前位置时,它会将我置于纬度 0 经度 0。如果我注释掉“// 启动:中心在 WA”部分,它会以用户当前位置,然后 goToLocation 工作正常。

如何让它以华盛顿州为中心,然后在单击 goToLocation 时缩放到用户当前位置?

谢谢!

- (void)viewDidLoad {

    [super viewDidLoad];
    [self loadOurAnnotations];
        [mapView setShowsUserLocation:NO];

// startup: center over WA
    CLLocationCoordinate2D defaultCoordinate;
    defaultCoordinate.latitude = 47.517201;
    defaultCoordinate.longitude = -120.366211;
    [mapView setRegion:MKCoordinateRegionMake(defaultCoordinate, MKCoordinateSpanMake(6.8, 6.8)) animated:NO];


}


-(IBAction)goToLocation {
    MKUserLocation *myLocation = [mapView userLocation];
    CLLocationCoordinate2D coord = [[myLocation location] coordinate];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 350, 350);
    [mapView setRegion:region animated:YES];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1];
    [UIView commitAnimations];
}

【问题讨论】:

    标签: ios mkmapview mapkit


    【解决方案1】:

    首先,要在MKMapView 中使用userLocation,您必须将YES 传递给setShowsUserLocation(而不是NO)。

    接下来就是开启showsUserLocation后,地图视图可能需要几秒或更长时间才能确定位置并设置userLocation。在此之前,该位置将为 nil(坐标为 0,0)。

    要真正知道 userLocation 何时准备好(或更新),请实现 didUpdateUserLocation 委托方法。在确定用户位置时遇到问题,实现didFailToLocateUserWithError 方法也很有帮助。

    但是,在您的情况下,您可以在 goToLocation 方法中执行以下操作:

    MKUserLocation *myLocation = [mapView userLocation];
    if (myLocation.location == nil)
    {
        NSLog(@"user location has not been determined yet");
        return;
    }
    CLLocationCoordinate2D coord = [[myLocation location] coordinate];
    MKCoordinateRegion region = ... //rest of the code stays the same
    

    顺便说一句,该方法末尾的动画语句不做任何事情。

    【讨论】:

    • 非常感谢您的帮助,安娜。我会修改的。
    猜你喜欢
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 2011-12-04
    • 1970-01-01
    相关资源
    最近更新 更多