Swift - 如何从gpx文件中读取坐标

J.P*_*ini 2 xcode gpx mkmapview ios swift

所以在我提出的另一个问题中,我发现我可以轻松创建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)
        }
Run Code Online (Sandbox Code Playgroud)

所以现在我把整个文本放在一个字符串中,但我不需要这一切:

<?xml version="1.0" encoding="UTF-8"?>
    <trk>
        <name>test</name>
        <desc>Length: 1.339 km (0.832 mi)</desc>
        <trkseg>
            <trkpt lat="-39.2505337" lon="-71.8418312"></trkpt>
            <trkpt lat="-39.2507414" lon="-71.8420136"></trkpt>
        </trkseg>
    </trk>
</gpx>
Run Code Online (Sandbox Code Playgroud)

我只需要<trkpt>标签之间的纬度和经度,这样我就可以将它们转换成位置,并从那里将其转换为MKPolygon.

任何帮助将非常感激,因为我没有在谷歌找到有关如何使用swift阅读gpx文件的任何内容.

在此先感谢-Jorge

J.P*_*ini 13

好的,我能够使用以下代码读取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 <trkpt> or <wpt> 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)!))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它对某人有帮助