jjzjj

ios - 从坐标数组到表格的位置之间的距离

coder 2023-09-14 原文

我试图用显示从坐标数组中的用户当前位置到位置的距离的行填充表格。我在一个空数组中有坐标,我有用户位置。

我坚持将坐标数组放入函数中以计算距离,然后将每个距离值放入表行中的标签中。非常感谢任何见解。

var locationArray: [CLLocationCoordinate2D] = []
var shopperLocation = String()
var distanceText: [String] = []

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0]

    shopperLocation = userLocation

    self.manager.stopUpdatingLocation()
}

//This is the function I am trying to use to get distance from the array of coordinates //

func distanceToLocation(){

    if locationArray == nil {

        locationArray = userLocation
    }

    let distanceBetween: CLLocationDistance =   shopperLocation.distanceFromLocation(startLocation) / 1609.34

    let distanceInMilesFromUser = String(format: "%.2f", distanceBetween)

    distanceText = "\(distanceInMilesFromUser) mi"
   }

  // Here I am trying to get the distance values in the correct rows //

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! listViewCell

    cell.myDistance.text = distanceText[indexPath.row]

    return cell
}

最佳答案

这是因为您必须明确告诉 TableView 重新加载数据,即再次询问其 TableViewDataSource 以使用新数据配置每个单元格。

您可以通过在 CLLocationManager 的委托(delegate)方法中调用 tableView.reloadData() 轻松地做到这一点。下面的代码是实现这一目标的一种方法。顺便提几点:

  • 我发现使用 var myArray = [Type]() 初始化数组比提供显式类型然后分配一个空数组更优雅

  • 您最好将商店参数(名称、坐标等)保存在结构中

  • 跟踪当前用户位置而不是距离;这样做将使您能够轻松添加新商店,而无需再次请求用户位置

  • 使用 MKDistanceFormatter 为您的距离获取人类可读的漂亮文本输出 — 这非常强大,并且可以免费适应您的用户的语言环境和首选单位系统!

不要忘记导入所有必需的模块:

import UIKit
import CoreLocation
import MapKit

定义常量:

let locationCellIdentifier = "LocationCell"

和你的结构:

struct Shop {
    let name: String
    let coordinates: CLLocation
}

然后是你的 View Controller :

final class LocationTableView: UITableViewController, CLLocationManagerDelegate {
    
    var shops = [Shop]()
    var userLocation: CLLocation?
    let distanceFormatter = MKDistanceFormatter()
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        // Save the location and reloads table view
        if !locations.isEmpty {
            userLocation = locations.first
            manager.stopUpdatingLocation()
            tableView.reloadData()
        }
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return shops.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(locationCellIdentifier, forIndexPath: indexPath)
        
        // Configure the cell
        let shop = shops[indexPath.row]
        cell.textLabel?.text = shop.name
        
        if let userLocation = userLocation {
            let distance = shop.coordinates.distanceFromLocation(userLocation)
            let formattedDistance = distanceFormatter.stringFromDistance(distance)
            cell.detailTextLabel?.text = formattedDistance
        } else {
            cell.detailTextLabel?.text = nil
        }
        
        return cell
    }
}

关于ios - 从坐标数组到表格的位置之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423147/

有关ios - 从坐标数组到表格的位置之间的距离的更多相关文章

  1. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  2. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  3. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  4. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  5. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  6. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  7. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  8. ruby - 在 Ruby 中用键盘诅咒数组浏览 - 2

    我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作

  9. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  10. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

随机推荐