如何使用 MapKit 跟踪用户位置
我使用 MapKit 来显示用户相对于周围图钉的位置。我希望能够模仿地图通过屏幕左下角的十字线按钮提供的功能。我已经知道 MapKit 通过 MKUserLocation 提供了带有用户位置的 CLLocation 对象,我只是想寻求有关如何关注该位置的建议。我最初的倾向是使用 NSTimer 每 500 毫秒左右将地图置于该坐标的中心。
有更好的方法吗? MapKit 中是否有我缺少的内置功能可以实现此目的?
非常感谢, 布伦丹
I'm using MapKit to display the user's location relative to pins around them. I'd like to be able to mimic the functionality that Maps provides via the crosshair button in the lower left-hand corner of the screen. I'm already aware that MapKit provides a CLLocation object with the user's location via MKUserLocation, I just wanted to seek advice on how I should keep focus on that location. My initial inclination was to use an NSTimer to center the map on that coordinate every 500ms or so.
Is there a better way to do this? Is there something built in to MapKit that I'm missing that will accomplish this?
Thanks so much,
Brendan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 IOS5+,这非常简单。只需使用以下代码更改“userTrackingMode”:
这将顺利跟踪用户当前位置。如果您拖动地图,它甚至会将跟踪模式设置回 MKUserTrackingModeNone ,这通常是您想要的行为。
If you're on IOS5+ this is VERY easy. Just change the "userTrackingMode" using code such as:
This will smoothly follow the users current location. If you drag the map it will even set the tracking mode back to
MKUserTrackingModeNone
which is usually the behaviour you want.让地图自动更新用户位置非常简单,就像谷歌地图一样。只需将 showUserLocation 设置为 YES
...然后实现 MKMapViewDelegate 以在位置更新时重新居中地图。
并允许用户缩放和缩放平移而不将视图偷回当前位置...
It's really simple to have the map update the user location automatically just like the google maps. Simply set showsUserLocation to YES
...and then implement the MKMapViewDelegate to re-center the map when the location is updated.
And to allow the user to zoom & pan without stealing the view back to the current location...
我认为我实际上会使用 CoreLocation
CLLocationManager
并使用其委托方法locationManager:didUpdateToLocation:fromLocation:
。这样,您就没有
NSTimer
的开销,并且它仅在有新位置可用时更新。您可以从发送到
locationManager:didUpdateToLocation:fromLocation:
方法的 CLLocation 对象中提取经度和纬度,并将其传递给地图视图。I think that I would actually use the CoreLocation
CLLocationManager
and use its delegate methodlocationManager:didUpdateToLocation:fromLocation:
.This way, you don't have the overhead of an
NSTimer
, and it only updates when there's a new location available.You can pull the longitude and latitude from the
CLLocation
object sent to thelocationManager:didUpdateToLocation:fromLocation:
method and pass it to the map view.我同意雅各布·雷尔金的回答。 本教程提供了使用 CoreLocation 的分步过程在 iPhone 应用程序中。希望这对您有帮助。
一切顺利。
I go with Jacob Relkin's answer. This tutorial provides a step-by-step procedure of using CoreLocation in an iPhone app. Hope this helps you.
All the Best.