【问题标题】:Updating the centre point & zoom of MKMapView (iPhone)更新 MKMapView (iPhone) 的中心点和缩放
【发布时间】:2011-11-25 12:07:05
【问题描述】:

我一直在尝试将地图视图集中在用户位置上。这也应该在注册位置更改时更新。我遇到的问题是在加载应用程序时我无法掌握当前的纬度和经度来应用居中和缩放。

这些是我目前掌握的关键代码...

- (void)viewDidLoad
{
    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

    [self updateMapZoomLocation:locationManager.location];

    [super viewDidLoad];
}

这个想法是它应该创建一个位置管理器的实例,然后开始更新位置。最后它应该运行我编写的函数来相应地更新地图视图......

- (void)updateMapZoomLocation:(CLLocation *)newLocation
{
    MKCoordinateRegion region;
    region.center.latitude = newLocation.coordinate.latitude;
    region.center.longitude = newLocation.coordinate.longitude;
    region.span.latitudeDelta = 0.1;
    region.span.longitudeDelta = 0.1;
    [map setRegion:region animated:YES];   
}

然而这似乎并没有发生。该应用程序构建并运行正常,但显示的只是黑屏 - 好像坐标不存在?!

我还有一个委托方法,通过调用上面的函数来处理任何更新......

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
           fromLocation:(CLLocation *)oldLocation
{
    [self updateMapZoomLocation:newLocation];
}

我已经尝试查看之前已经提出和回答的其他几个类似问题,但我似乎仍然找不到我想要的解决方案。

对此的任何帮助将不胜感激;我花了好几个小时在互联网上寻找帮助和解决方案。

ps。 'map' 是 mapView。

【问题讨论】:

  • locationManager:didUpdateToLocation:fromLocation 被调用了吗?或者它被调用但你没有得到一个有效的位置?您应该丢弃 newLocation 具有负水平精度(表示它无效)的任何位置更新。将 NSLog 添加到 locationManager:didUpdateToLocation:fromLocation 以显示水平精度和纬度/经度,并将该信息包含在您的问题中。

标签: objective-c ios4 mkmapview core-location latitude-longitude


【解决方案1】:

您想使用 MKMapViewDelegate 回调,以便仅在实际知道位置后放大:

这里有一些快速的代码来处理这个问题:

var alreadyZoomedIn = false

func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
    if(!alreadyZoomedIn) {
        self.zoomInOnCurrentLocation()
        alreadyZoomedIn = true
    }
}

func zoomInOnCurrentLocation() {

        var userCoordinate = mapView?.userLocation.coordinate
        var longitudeDeltaDegrees : CLLocationDegrees = 0.03
        var latitudeDeltaDegrees : CLLocationDegrees = 0.03
        var userSpan = MKCoordinateSpanMake(latitudeDeltaDegrees, longitudeDeltaDegrees)
        var userRegion = MKCoordinateRegionMake(userCoordinate!, userSpan)

        mapView?.setRegion(userRegion, animated: true)
}

【讨论】:

    【解决方案2】:

    您不应在 viewDidLoad 函数期间调用 updateMapZoomLocation,因为位置管理器尚未找到位置。如果/当它完成时,它会在它准备好时调用委托函数。在那之前,您的地图将不知道在哪里居中。您可以尝试尽可能远地缩小,或者记住在应用关闭之前它最后一次查看的位置。

    【讨论】:

    • 我已经尝试过了,但是当我运行模拟器时,它似乎并没有更新那个位置并放大。这可能只是因为模拟器不会更新它的位置吗?
    • 刚刚尝试在我的 iPhone 上运行它,它按预期工作 - 谢谢!
    • 启动位置管理器时模拟器只发送一个位置,它是苹果在库比蒂诺的总部。如果您是注册开发人员(我认为您必须将其部署到设备上),您会对本页底部的developer.apple.com/technologies/ios5 感兴趣
    猜你喜欢
    • 2010-11-13
    • 2018-12-21
    • 1970-01-01
    • 2012-11-14
    • 2015-06-22
    • 2015-07-08
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多