【问题标题】:Determining distance using mapkit使用 mapkit 确定距离
【发布时间】:2016-11-11 06:21:34
【问题描述】:

如何使用 mapkit 确定 1000 英尺或 1/2 英里的距离?某个引脚的半径或两个引脚之间的距离。

例如,我将地图置于引脚 A 的中心。引脚 B、C 和 D 也在地图上与引脚 A 的不同距离处。B 和 C 距离 A 1/2 英里,但 D 距离 1 英里.我想知道 B 和 C 距离 A 不到 1/2 英里。我该如何计算?

【问题讨论】:

  • 您能否详细解释一下您的问题,以便我们了解具体要求?
  • 我已编辑问题。如果您需要更多信息,请告诉我。

标签: iphone cocoa-touch mapkit


【解决方案1】:

由于您已声明两个不同的点是“引脚”,我将假设您使用的是 MKPinAnnotationView(或其他一些注释视图)。如果没有,您将不得不通过其他方式获取该位置。

如果您有指向这些位置的注释对象的指针,那么您可以轻松地在它们上调用-coordinate,从这些坐标创建CLLocations(使用-initWithLatitude:longitude:),然后使用方法-getDistanceFrom 检索距离以米为单位。从那里,很容易转换成里程。总而言之,代码看起来像这样:

CLLocationCoordinate2D pointACoordinate = [pointAAnnotation coordinate];
CLLocation *pointALocation = [[CLLocation alloc] initWithLatitude:pointACoordinate.latitude longitude:pointACoordinate.longitude];
CLLocationCoordinate2D pointBCoordinate = [pointBAnnotation coordinate];
CLLocation *pointBLocation = [[CLLocation alloc] initWithLatitude:pointBCoordinate.latitude longitude:pointBCoordinate.longitude];
double distanceMeters = [pointALocation getDistanceFrom:pointBLocation];
double distanceMiles = (distanceMeters / 1609.344);

您最终会得到以英里为单位的距离,并且可以从那里进行比较。希望这会有所帮助。

【讨论】:

  • 好的,但是这样我们就可以得到两点之间的直线距离......不是实际的如何找到这个实际距离......
【解决方案2】:

getDistanceFrom 现在已弃用,因此对于任何想要这样做的人来说,这里有一个替代答案。

CLLocationCoordinate2D pointACoordinate = [pointAAnnotation coordinate];
CLLocation *pointALocation = [[CLLocation alloc] initWithLatitude:pointACoordinate.latitude longitude:pointACoordinate.longitude];  

CLLocationCoordinate2D pointBCoordinate = [pointBAnnotation coordinate];
CLLocation *pointBLocation = [[CLLocation alloc] initWithLatitude:pointBCoordinate.latitude longitude:pointBCoordinate.longitude];  

float distanceMeters = [pointALocation distanceFromLocation:pointBLocation];
float distanceMiles = (distanceMeters / 1609.344);  

[pointALocation release];
[pointBLocation release];  

如上所述,您可以使用float 而不是double,如果您不需要float 的精度,您可以将结果转换为int,如下所示:

int distanceCastToInt = (int) [pointALocation distanceFromLocation:pointBLocation];

如果您想在注释中大致了解距离,int 很方便,如下所示:

pointAAnnotation.title = @"Point A";
pointAAnnotation.subtitle = [NSString stringWithFormat: @"Distance: %im",distanceCastToInt];

注解的副标题例如是“距离:50m”。

【讨论】:

    【解决方案3】:

    这是给定答案的 Swift 3 等效项:

    let pointACoordinate = pointAAnnotation.coordinate
    let pointALocation = CLLocation(latitude: pointACoordinate.latitude, longitude: pointACoordinate.longitude)
    let pointBCoordinate = pointBAnnotation.coordinate
    let pointBLocation = CLLocation(latitude: pointBCoordinate.latitude, longitude: pointBCoordinate.longitude)
    let distanceMeters = pointALocation.distance(from: pointBLocation)
    let distanceMiles = (distanceMeters / 1609.344)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      相关资源
      最近更新 更多