快速写入和访问类对象

时间:2017-05-27 20:57:23

标签: ios class swift3

所以我试图使用MapKit将一系列点放入地图中。 Ultimitely我将从csv获取数据点列表并将它们加载到Location Class中,然后从Class中读取它们作为MapView Annotations。这可以单独用于手动绘制2个点...但我无法弄清楚如何正确加载和访问许多项目的位置类(例如10个位置点)

这是我的班级文件

import Foundation
import MapKit

class Location: NSObject, MKAnnotation{
    let title: String?
    let locationName: String
    let discipline: String
    let coordinate: CLLocationCoordinate2D

    init(title: String, locationName: String, lat: String, lon: String){
        self.title = title
        self.locationName = locationName
        let latDouble = (lat as NSString).doubleValue
        let lonDouble = (lon as NSString).doubleValue
        let latlong = CLLocationCoordinate2D(latitude: latDouble, longitude: lonDouble)
        self.discipline = locationName
        self.coordinate = latlong
        super.init()
    }
}

这里是ViewController.swift

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    //var stops = TransitStop[]()
    let initialLocation = CLLocation( latitude: 41.880632, longitude: -87.623277)
    @IBOutlet weak var mapView: MKMapView!
    let regionRadius: CLLocationDistance = 1000

    override func viewDidLoad() {
        super.viewDidLoad()
        let initial = Location(title: "YOU", locationName: "are here", lat: "41.880632", lon: "-87.623277")
        let firstStop = Location(title: "ashland", locationName: "ashland", lat: "41.88574", lon: "-87.627835")// Do any additional setup after loading the view, typically from a nib.
        centerMapOnLocation(location: initialLocation)

        mapView.addAnnotation(initial)
        mapView.addAnnotation(firstStop)
    }

    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
        mapView.setRegion(coordinateRegion, animated: true)
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

   var locationArray: [Location] = []
    for line in csvString{
        let values:[String] = line.components(separatedBy: ",")
        let title = values[0]
        let locationName = values[1]
        let lat = values[2]
        let lng = values[3]

        let latD: Double = Double(lat)
        let lngD: Double = Double(lng)

        let location = Location(title: title, locationName: locationName, lat: latD, lng: lngD)
        locationArray.append(location)
    }
    centerMapOnLocation(location: initialLocation)

    addLocationsToMap(locationArray: locationArray)

确保在实施之前对值(Double)进行一些验证。 然后,您可以使用此功能将位置读入地图:

func addLocationsToMap(locationArray: [Location]){
    for location in locationArray {
        mapView.addAnnotation(location)
    }
}

注意:我意识到OP不需要明确定义变量。我只是觉得它会更容易理解。

我假设可以从数组中读取csv值,并且可以在csv文件中将值放置在' title',' loacationName'很明确。