如何使文本显示距离从用户当前位置到某个Map注释

时间:2016-07-29 00:00:41

标签: uitableview mkmapview ios9 mkannotation xcode7.3

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

非常感谢您的帮助谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用let newYork = CLLocation(latitude: 40.725530, longitude: -73.996738) let sanFrancisco = CLLocation(latitude: 37.768, longitude: -122.441) let distanceInMeters = newYork.distanceFromLocation(sanFrancisco) 方法计算两个CLLocation对象之间的距离:

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) ... } 对象,您可以按如下方式计算用户当前位置和注释之间的距离:

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
  }
}

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

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
  }
}

将所有这些放在一起可以得到以下结论:

render: function() {
    return (
      <FormControl componentClass="select" onChange={console.log("changed")}>
                    <option value="1">A</option>         
                    <option value="2">B</option>         
      </FormControl>                       
    );
  }
相关问题