Swift – 如何从gpx文件中读取坐标
所以在我提出的另一个问题中,我发现我可以轻松创建gpx文件,但现在我需要将gpx文件的内容显示为MKPolygon。 之前,我创建了包含plist文件中所有坐标的列表,这很容易阅读,因为我可以制作一个NSDictionary并从那里读取并使用plist提供的键找到位置,但它不是似乎在gpx文件中很容易。
我创建了这个小的代码段来读取gpx文件的全部内容:
if fileManager.fileExistsAtPath(filePath) { let dataBuffer = NSData(contentsOfFile: filePath) let dataString = NSString(data: dataBuffer!, encoding: NSUTF8StringEncoding) print (dataString) }
所以现在我把整个文本放在一个字符串中,但我不需要这一切:
test Length: 1.339 km (0.832 mi)
我只需要标签之间的纬度和经度,这样我就可以将它们转换成位置,并从那里将其转换为MKPolygon。
任何帮助将不胜感激,因为我还没有在google上找到有关如何使用swift读取gpx文件的任何内容。
在此先感谢-Jorge
好的,我能够使用以下代码读取gpx文件:
import Foundation import MapKit //NSXMLParserDelegate needed for parsing the gpx files and NSObject is needed by NSXMLParserDelegate class TrackDrawer: NSObject, NSXMLParserDelegate { //All filenames will be checked and if found and if it's a gpx file it will generate a polygon var fileNames: [String]! = [String]() init(fileNames: [String]) { self.fileNames = fileNames } //Needs to be a global variable due to the parser function which can't return a value private var boundaries = [CLLocationCoordinate2D]() //Create a polygon for each string there is in fileNames func getPolygons() -> [MKPolygon]? { //The list that will be returned var polyList: [MKPolygon] = [MKPolygon]() for fileName in fileNames! { //Reset the list so it won't have the points from the previous polygon boundaries = [CLLocationCoordinate2D]() //Convert the fileName to a computer readable filepath let filePath = getFilePath(fileName) if filePath == nil { print ("File \"\(fileName).gpx\" does not exist in the project. Please make sure you imported the file and dont have any spelling errors") continue } //Setup the parser and initialize it with the filepath's data let data = NSData(contentsOfFile: filePath!) let parser = NSXMLParser(data: data!) parser.delegate = self //Parse the data, here the file will be read let success = parser.parse() //Log an error if the parsing failed if !success { print ("Failed to parse the following file: \(fileName).gpx") } //Create the polygon with the points generated from the parsing process polyList.append(MKPolygon(coordinates: &boundaries, count: boundaries.count)) } return polyList } func getFilePath(fileName: String) -> String? { //Generate a computer readable path return NSBundle.mainBundle().pathForResource(fileName, ofType: "gpx") } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { //Only check for the lines that have a or tag. The other lines don't have coordinates and thus don't interest us if elementName == "trkpt" || elementName == "wpt" { //Create a World map coordinate from the file let lat = attributeDict["lat"]! let lon = attributeDict["lon"]! boundaries.append(CLLocationCoordinate2DMake(CLLocationDegrees(lat)!, CLLocationDegrees(lon)!)) } } }
我希望它对某人有帮助