【问题标题】:How to make Text Show distance from The user current location to a certain Map annotation如何使文本显示从用户当前位置到某个地图注释的距离
【发布时间】:2016-07-29 00:00:41
【问题描述】:

只是想知道如何做到这一点,真的很想在我的应用程序的表格视图中的自定义单元格中这样做......

将不胜感激任何帮助谢谢!

【问题讨论】:

  • 什么是文字计算距离?
  • 就像在自定义 TableViewCell 中一样,我会放一个标签或其他东西,它会告诉我与某个注释的距离
  • 你明白了吗?
  • 你是问如何计算用户当前位置与annotation所代表位置的距离?
  • 正是我的意思!

标签: uitableview mkmapview ios9 mkannotation xcode7.3


【解决方案1】:

您可以使用distanceFromLocation 方法计算两个CLLocation 对象之间的距离:

let newYork = CLLocation(latitude: 40.725530, longitude: -73.996738)
let sanFrancisco = CLLocation(latitude: 37.768, longitude: -122.441)
let distanceInMeters = newYork.distanceFromLocation(sanFrancisco)

使用MKMapView对象和MKAnnotationView对象,可以计算出用户当前位置与注解之间的距离,如下:

if let userLocation = mapView.userLocation.location, annotation = annotationView.annotation {
  // Calculate the distance from the user to the annotation
  let annotationLocation = CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude)
  let distanceFromUserToAnnotationInMeters = userLocation.distanceFromLocation(annotationLocation)
  ...
}

以下函数使用NSNumberFormatter 类来格式化以米或公里为单位的距离(如果米数超过 1000):

func formatDistance(distanceInMeters: CLLocationDistance) -> String? {
  // Set up a number formatter with two decimal places
  let numberFormatter = NSNumberFormatter()
  numberFormatter.numberStyle = .DecimalStyle
  numberFormatter.maximumFractionDigits = 2

  // Display as kilometers if the distance is more than 1000 meters
  let distanceToFormat: CLLocationDistance = distanceInMeters > 1000 ? distanceInMeters/1000.0 : distanceInMeters
  let units = distanceInMeters > 1000 ? "Km" : "m"

  // Format the distance
  if let formattedDistance = numberFormatter.stringFromNumber(distanceToFormat) {
    return "\(formattedDistance)\(units)"
  } else {
    return nil
  }
}

把所有这些放在一起,我们得到了以下结果:

if let userLocation = mapView.userLocation.location, annotation = annotationView.annotation {
  // Calculate the distance from the user to the annotation
  let annotationLocation = CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude)
  let distanceFromUserToAnnotationInMeters = userLocation.distanceFromLocation(annotationLocation)
  if let formattedDistance = formatDistance(distanceFromUserToAnnotationInMeters) {
    // Now set the vaue of your label to formattedDistance
  }
}

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多