【问题标题】:Append Json Array with Calculated Lat and Long使用计算的纬度和经度追加 Json 数组
【发布时间】:2018-05-28 15:38:23
【问题描述】:

我收到了一组 JSON 格式的餐厅位置。我想计算与用户的距离,并且只显示离我的用户最近的位置。我已将数据提取到一个函数中并计算了纬度和经度,并且我将用户的纬度和经度保存在一个名为距离的变量中,但是,我不确定如何:

  • 将纬度/经度附加到数组中的每个项目以及场地信息
  • 计算与用户的距离
  • 打印出该半径内出现的所有场地。

这是我的功能:

func loadRestaurantss() {
    Helpers.showActivityIndicator(activityIndicator, view)

    APIManager.shared.getRestaurantss { (json) in
        if json != nil {
            self.restaurants = []
            self.filterArray = []
            //Adds all items into the array list dist then goes through them all.
            if let listDis = json["restaurant"].array {
                for item in listDis {
                    let address = item["street_address"].string! + ", " + item["city"].string! + ", " + item["state"].string!

                    self.getLocation(address, { (dis) in
                        self.disLocation = dis
                        self.venueLatt = (self.disLocation?.coordinate.latitude)!
                        self.venueLonn = (self.disLocation?.coordinate.longitude)!
                    })

                    if let snapValue = item.array,
                        let venueLat = self.venueLatt as? Double,
                        let venueLong = self.venueLonn as? Double {
                    }

                    let restaurant = Restaurant(json: item)
                    self.restaurants.append(restaurant)
                }
                print("Dis Test: ", self.restaurants)

                self.tbvRestaurants.reloadData()
                Helpers.hideActivityIndicator(self.activityIndicator)
            }
        }
    }
}

计算用户和场地距离的变量:

 let distance = self.calculateDistance(userlat: self.userLatt, userLon: self.userLonn, venueLat: venueLat, venueLon: venueLong)

项目数组的输出:

Item: {
  "state" : "Arizona",
  "city" : "Phoenix",
  "id" : 2,
  "restaurant_name" : "Restaruant  2",
  "street_address" : "123 Fake Street",
  "zip_Code" : 89801,
  "phone" : "123-456-1234",
  "logo" : "http:\/\/foodonthego-.herokuapp.com\/media\/Restaurant_logo\/Phoenix-location_DWt73h5.jpg"
}

从这里我将 Lat 和 long 的值分别存储在 VenueLatt/Long 中。我需要将它们添加到数组中。这就是 SnapValue 正在做的事情,但是,我意识到数组没有附加并且总是失败。我环顾四周,但找不到解决方案。

【问题讨论】:

  • 我会设置断点以确保您将其放入if-let。如果您要进入if-let,我会确保您的Restaurant 构造函数不会返回nil

标签: ios arrays swift


【解决方案1】:

要计算距离,您可以使用核心位置 api。

简单示例:

import CoreLocation

// user location
var userLocation = CLLocation(latitude: 59.244696, longitude: 17.813868)

// venue location
var venueLocation = CLLocation(latitude: 59.326354, longitude: 18.072310)

// measure the distance (in km)
var distance = userLocation.distanceFromLocation(venueLocation) / 1000

【讨论】:

  • 如何将其添加到包含位置的数组中?
  • 我不知道Restaurant的类型。但我建议您向其中添加一个成员变量,以便您可以存储与用户的距离。使用您提供的 sn-p,我看不到 Restaurant 中的数据是如何存储的。
猜你喜欢
  • 2014-03-19
  • 2010-09-28
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多