gpt4 book ai didi

Swift MKMapItems 与用户位置的距离

转载 作者:行者123 更新时间:2023-11-28 06:21:32 24 4
gpt4 key购买 nike

有人可以帮我理解我需要添加什么来获取用户位置和地标之间的距离吗?我只是不确定要更改 distanceLabel.text 中的内容以使每个地标的数字发生变化。谢谢!

import UIKit
import MapKit

class ListedMapTableViewController: UITableViewController, CLLocationManagerDelegate {

var mapItems: [MKMapItem]!
var userLocation = CLLocationManager()
let distanceFormatter = MKDistanceFormatter()


override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mapItems.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath) as! ListedTableViewCell

// Configure the cell...
let row = indexPath.row
let item = mapItems[row]
cell.nameLabel.text = item.name
cell.detailLabel.text = item.phoneNumber
let distanceInMeters : Double = self.userLocation.location!.distance(from: mapItems[row].placemark.location!)
let distanceInMiles : Double = ((distanceInMeters.description as String).doubleValue * 0.00062137)
cell.distanceLabel.text = "\(distanceInMiles.string(2)) miles away"

return cell
}

}


extension String {
var doubleValue: Double {
return (self as NSString).doubleValue
}
}

//formats a double's decimal places
extension Double {
func string(_ fractionDigits:Int) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = fractionDigits
formatter.maximumFractionDigits = fractionDigits
return formatter.string(from: NSNumber(value: fractionDigits))!
}
}

最佳答案

CLLocation 有一个 distanceFromLocation 方法,所以给定两个 CLLocations:

CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];

或者在 Swift 3 中:

//: Playground - 名词:人们可以玩耍的地方

import CoreLocation


let coordinate₀ = CLLocation(latitude: 5.0, longitude: 5.0)
let coordinate₁ = CLLocation(latitude: 5.0, longitude: 3.0)

let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters

你到这里的距离以米为单位,所以 1 英里 = 1609 米

if(distanceInMeters <= 1609)
{
// under 1 mile
}
else
{
// out of 1 mile
}

关于Swift MKMapItems 与用户位置的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43308991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com