ios - 如何计算我当前位置与 MapView 中其他 Pin 之间的距离

标签 ios mkmapview distance

我是 Swift 的新手,我需要计算我当前位置周围最近的地方。你能告诉我应该使用哪个函数来计算我的位置和我周围最近的位置之间的距离吗?我必须在应用程序中显示距离和地点,以便用户可以选择最适合他的。我认为我应该使用可以与我的进行比较的纬度和经度坐标。我还发现我必须使用 distanceFromLocation ,但我不知道如何使用,如果有人给我提供一个我可以用于我的代码的示例,我会很高兴。 到目前为止我的代码是:

 class ViewThree: UIViewController, CLLocationManagerDelegate{
@IBOutlet weak var SegmentControl: UISegmentedControl!
@IBOutlet weak var Mapview: MKMapView!


var manager =  CLLocationManager()
var receiveImeNaSladkarnica: String = ""
var KordaA: String = ""
var KordaB: String = ""
var PodImeNaObekt: String = ""

  override func viewDidLoad() {
super.viewDidLoad()


    let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake((KordaA as NSString).doubleValue,(KordaB as NSString).doubleValue)
    let objectAnn = MKPointAnnotation()
    objectAnn.coordinate = pinLocation
    objectAnn.title = receiveImeNaSladkarnica
    objectAnn.subtitle = PodImeNaObekt
    self.Mapview.addAnnotation(objectAnn)

 }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func Directions(sender: AnyObject) {
    UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/maps?daddr=\((KordaA as NSString).doubleValue),\((KordaB as NSString).doubleValue))")!)



}

@IBAction func MapType(sender: AnyObject) {
    if (SegmentControl.selectedSegmentIndex == 0){
        Mapview.mapType = MKMapType.Standard
    }
    if (SegmentControl.selectedSegmentIndex == 1){
        Mapview.mapType = MKMapType.Satellite
    }


}

@IBAction func LocateMe(sender: AnyObject) {
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

    Mapview.showsUserLocation = true



}
func  locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userlocation: CLLocation = locations[0] as CLLocation
    manager.stopUpdatingLocation()
    let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
    let span = MKCoordinateSpanMake(0.5, 0.5)
    let region = MKCoordinateRegion(center: location, span: span)
    Mapview.setRegion(region, animated: true )
}

最佳答案

我在另一个应用程序中遇到了相同的情况。

CLLocation对象中,有一个实例函数:

func distanceFromLocation(location: CLLocation) -> CLLocationDistance

//Get your two locations that you want to calculate the distance from:

let userLocation: CLLocation = ...
let locationToCompare: CLLocation = ...

// Returned value is in meters
let distanceMeters = userLocation.distanceFromLocation(locationToCompare)

// If you want to round it to kilometers
let distanceKilometers = distanceMeters / 1000.00

// Display it in kilometers
let roundedDistanceKilometers = String(Double(round(100 * distanceKilometers) / 100)) + " km"

已更新

针对您的用例

let locations = ... // All locations you want to compare

for location in locations {

    let distanceMeters = userLocation.distanceFromLocation(location)

    if distanceMeters > 5000 { // Some distance filter
          // Don't display this location
    } else {
          // Display this location
    }

}

我的代码: 改进

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userlocation:CLLocation = locations[0] as CLLocation

    manager.stopUpdatingLocation()

    let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)

    let span = MKCoordinateSpanMake(0.5, 0.5)

    let region = MKCoordinateRegion(center: location, span: span)

    Mapview.setRegion(region, animated: true)

    let locationStrings = ["42.6977,23.3219","43.6977,24.3219"]

    // This array must be an array that contains CLLocation objects        
    var locations: [CLLocation] = []

    // We must retrieve the latitude and longitude from locationStrings array to convert them into CLLocation objects
    for locationString in locationStrings {

        let location = CLLocation(latitude: <latitude_value>, longitude: <latitude_value>)

        locations.append(location)

    }

    // Then you will be able to enumerate through the array
    for location in locations {

        let distanceMeters = userLocation.distanceFromLocation(location)

        if distanceMeters > 5000 { // Some distance filter
            // Don't display this location
        } else {
            // Display this location
        }

    }

关于ios - 如何计算我当前位置与 MapView 中其他 Pin 之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38960997/

相关文章:

ios - App Store证书/ key 对代码签名过程中是否存在 "screw it up permanently"情况?

swift - 计算 MKMapView 中 MKPolygon 的面积

ios - 为什么我不能在 map View 上添加渐变?

vector - 计算两个不同长度的向量之间的距离

iOS webbrowser会自动关闭websocket连接吗?

ios - 在 iOS 10.x 中以编程方式获取 CellID 和 LAC

ios - UITableViewCell 中的自定义 UIView 阻止 uitableviewcell 接收事件

ios - 当用户位置更新或使用默认值时刷新 MKMapView

android - 使用红外激光传感器 Nexus 6P 和 5X 测量距离

r - 对 2 个距离矩阵求和以获得第三个 'overall' 距离矩阵(生态环境)