如何在没有CLLocationManager的情况下将MKMapView缩放到用户当前位置? [英] How do I zoom an MKMapView to the users current location without CLLocationManager?

查看:71
本文介绍了如何在没有CLLocationManager的情况下将MKMapView缩放到用户当前位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 MKMapView ,有一个名为显示用户当前位置的选项,它会自动显示地图上的用户位置

With the MKMapView there's an option called "Show users current location" which will automatically show a users location on the map.

我想在找到它时移动并缩放到这个位置(如果它发生变化)。

I'd like to move and zoom to this location when it's found (and if it changes).

问题是,当在地图上更新用户位置时似乎没有调用任何方法,所以我无处可以放置代码将缩放/滚动

The problem is, there doesn't appear to be any method called when the user location is updated on the map, so I have nowhere to put the code that will zoom/scroll.

有什么方法可以在 MKMapView <时收到通知/ code>已经(或更新)了用户位置,所以我可以移动/缩放它?如果我使用自己的 CLLocationManager ,我得到的更新与地图上用户标记的更新不一致,所以当我的地图移动并缩放时,它看起来很傻蓝色别针出现。

Is there a way to be notified when an MKMapView has got (or updated) the user location so I can move/zoom to it? If I use my own CLLocationManager the updates I get do not correspond with the updates of the user marker on the map, so it looks silly when my map moves and zooms seconds before the blue pin appears.

这感觉就像基本的功能,但我花了几周的时间寻找解决方案而不是近距离接触。

This feels like basic functionality, but I've spent weeks looking for a solution and not turned up anything close.

推荐答案

您必须注册 userLocation.location 的KVO通知 MKMapView的属性

You have to register for KVO notifications of userLocation.location property of MKMapView.

为此,请将此代码放入ViewController的 viewDidLoad:或在地图视图初始化的地方的任何地方。

To do this, put this code in viewDidLoad: of your ViewController or anywhere in the place where your map view is initialized.

[self.mapView.userLocation addObserver:self  
        forKeyPath:@"location"  
           options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)  
           context:NULL];

然后实施此方法以接收KVO通知

Then implement this method to receive KVO notifications

- (void)observeValueForKeyPath:(NSString *)keyPath  
                      ofObject:(id)object  
                        change:(NSDictionary *)change  
                       context:(void *)context {  

    if ([self.mapView showsUserLocation]) {  
        [self moveOrZoomOrAnythingElse];
        // and of course you can use here old and new location values
    }
}

这段代码对我来说很好。

BTW, self 是我在此上下文中的ViewController。

This code works fine for me.
BTW, self is my ViewController in this context.

这篇关于如何在没有CLLocationManager的情况下将MKMapView缩放到用户当前位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆