如何使用JSON文件中的信息填充数组并计算距离? [英] How to populate an array with information from JSON File and calculate distance?

查看:94
本文介绍了如何使用JSON文件中的信息填充数组并计算距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个JSON文件:

I have a JSON File here:

     {
      "People": [{
       "A1": "New York",
       "B1": "ShoppingMall1",
       "C1": "43.0757",
       "D1": "23.6172"
       },
       {
       "A1": "London",
       "B1": "ShoppingMall2",
       "C1": "44.0757",
       "D1": "24.6172"
       }, {
       "A1": "Paris",
       "B1": "ShoppingMall3",
       "C1": "45.0757",
       "D1": "25.6172"
       }, {
       "A1": "Bern",
       "B1": "ShoppingMall4",
       "C1": "41.0757",
       "D1": "21.6172"
       }, {
       "A1": "Sofia",
       "B1": "ShoppingMall5",
       "C1": "46.0757",
       "D1": "26.6172"

       }
       ]
       }

,从这个JSON文件中,我必须获取购物中心的名称和坐标,并将其填充到一个数组中.我想在表格视图"单元格中使用此数组.主要思想是计算用户当前位置附近最近的购物中心.在这里,我计算了用户的当前位置.

and from this JSON File I have to take the names and the coordinates of the shopping malls and populate them into an array. This array I want to use in Table View Cells. The main idea is calculating the nearest shopping malls around the user's current location. Here I calculate the user's current location.

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




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

   }
   let distanceMeters = userlocation.distanceFromLocation(CLLocation(latitude: ??,longitude: ??))
let distanceKilometers = distanceMeters / 1000.00
let roundedDistanceKilometers = String(Double(round(100 * distanceKilometers) / 100)) + " km"

但是我不知道如何获取所有购物中心的坐标并进行比较,我也不知道如何将它们填充到需要用于表格视图单元格的数组中.如果有人可以帮助我,我会很高兴.

But I do not know how to take all of the shopping malls coordinates and compare them.I also do not how to populate them into an array which I need to use for the Table View Cells.I am new in swift and I will be glad if someone can help me with that.

推荐答案

我一直在研究您的问题,这是我的结果,

I had been working on your question and this are my results,

首先,我建议您使用一个JSON framework,例如SwiftyJSON,但是我不使用任何一个,因为我不知道您是否愿意,所以

First of all I recommend you to use one JSON framework such as SwiftyJSON but I don't use any because I don't know if you want to, so

首先,我们需要使用此代码加载json

first we need to load our json using this code

let pathForPlist = NSBundle.mainBundle().pathForResource("JSON", ofType: "json")!
let JSONData = NSData(contentsOfFile: pathForPlist)

我们需要解析这些数据并转换为JSONObject

after we need to parse this data and convert to JSONObject

let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]

并使用Dictionary中的初始化程序将其正确转换为对象,请注意,由于我们的json是字典数组,因此我们使用NSJSONReadingOptions.MutableContainers

and convert to properly Objects using an initializer from Dictionary, note that we use NSJSONReadingOptions.MutableContainers because our json is an array of dictionaries

这是完整的代码,请注意,我为您的数据类型定义了一个名为ObjectShop的类,以帮助以后进行计算

this is the full code, note that I define a class for your data type named ObjectShop to help with the calculation later

import UIKit
import MapKit

class ObjectShop
{
    var A1 = ""
    var B1 = ""
    var C1 = ""
    var D1 = ""

    init?(dict:[String:AnyObject])
    {
        A1 = dict["A1"] as! String
        B1 = dict["B1"] as! String
        C1 = dict["C1"] as! String
        D1 = dict["D1"] as! String
    }

    func getCoordenate2D() -> CLLocationCoordinate2D
    {
        return CLLocationCoordinate2D(latitude: Double(self.C1)!, longitude: Double(self.D1)!)
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let pathForPlist = NSBundle.mainBundle().pathForResource("JSON", ofType: "json")!
        let JSONData = NSData(contentsOfFile: pathForPlist)
        do
        {
            var objects = [ObjectShop]()
            let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
            print(JSONObject)
            for dic in JSONObject["People"] as! [[String:AnyObject]] {
                print(dic)
                let objc = ObjectShop(dict: dic)
                objects.append(objc!)
            }

            for object in objects {
                print(object.getCoordenate2D())
            }
        }
        catch _
        {

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

希望这对您有所帮助,如果您有任何疑问,请告诉我

I hope this helps you, let me know if you have any question

这篇关于如何使用JSON文件中的信息填充数组并计算距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆