使用 Mapkit 确定距离
如何使用 Mapkit 确定 1000 英尺或 1/2 英里距离?某个销钉的半径或两个销钉之间的距离。
例如,我将地图以引脚 A 为中心。引脚 B、C 和 D 也位于地图上,与引脚 A 的距离不同。B 和 C 距离 A 不到 1/2 英里,但 D 距离 1 英里。我想知道 B 和 C 距离 A 不超过 1/2 英里。我该如何计算?
How is a 1000ft or 1/2 mile distance determined with mapkit? Either a radius from some pin or the distance between two pins.
For example, I center the map on pin A. Pins B, C, and D are also on the map at various distances from pin A. B and C are within 1/2 mile from A but D is 1 mile away. I'd like to know that B and C are within 1/2 mile from A. How can I calculate that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
既然您已经声明这两个不同的点是“引脚”,我将假设您正在使用 MKPinAnnotationView (或其他一些注释视图)。如果没有,您将不得不通过其他方式获取该位置。
如果您有指向这些位置的注释对象的指针,那么您可以轻松地对它们调用
-coordinate
,从这些坐标创建 CLLocations(使用-initWithLatitude:longitude:
),然后使用方法-getDistanceFrom
检索以米为单位的距离。从那里,可以轻松转换为英里。总而言之,代码看起来像这样:您最终会得到以英里为单位的距离,并可以从那里进行比较。希望这有帮助。
Since you've stated that the two different points are "pins", I'm going to assume you're using MKPinAnnotationView (or some other annotation view). If not, you're going to have to get the location some other way.
If you have pointers to the annotation objects for these locations, then you can easily call
-coordinate
on them, create CLLocations from these coordinates (using-initWithLatitude:longitude:
), and then use the method-getDistanceFrom
to retrieve the distance in meters. From there, it's an easy conversion to miles. All told, the code would look something like this:You'll end up with the distance in miles, and can compare it from there. Hope this helps.
getDistanceFrom
现已弃用,因此对于任何想要执行此操作的人来说,这是一个替代答案。如上所述,您可以使用
float
而不是double
,并且如果您不需要float
的精度,则可以将结果转换为 int > 像这样:如果您想在注释中粗略地了解距离,
int
会很方便,如下所示:例如,注释的副标题将显示“距离:50m”。
getDistanceFrom
is now deprecated so here's an alternative answer for anyone looking to do this.As above, you could use
float
instead ofdouble
and you could cast the results to an int if you don't require the precision of thefloat
like so:The
int
is handy if you wanted to give a rough idea of distance in the annotation like so:The subtitle of the annotation would read "Distance: 50m" for example.
这在 Swift 3 中相当于给定的答案:
This is Swift 3 equivalent of the given answer: