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

4
在我之前提出的其他问题中,我发现可以轻松创建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)
        }

所以现在我有了一个字符串中的整个文本,但我不需要这些全部内容:
<?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>

我只需要<trkpt>标签之间的纬度和经度,以便将其转换为位置,并从那里将其转换为MKPolygon。
由于我在谷歌上没有找到如何使用Swift读取gpx文件的任何信息,因此任何帮助都将不胜感激。
提前致谢 -Jorge
2个回答

16

好的,我能够使用以下代码读取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)!))
        }
    }
}

我希望这能帮助到某些人


2

简洁的方式

import Foundation
import CoreLocation

class Parser {
    private let coordinateParser = CoordinatesParser()

    func parseCoordinates(fromGpxFile filePath: String) -> [CLLocationCoordinate2D]? {
        guard let data = FileManager.default.contents(atPath: filePath) else { return nil }
    
        coordinateParser.prepare()
    
        let parser = XMLParser(data: data)
        parser.delegate = coordinateParser

        let success = parser.parse()
    
        guard success else { return nil }
        return coordinateParser.coordinates
    }
}

class CoordinatesParser: NSObject, XMLParserDelegate  {
    private(set) var coordinates = [CLLocationCoordinate2D]()

    func prepare() {
        coordinates = [CLLocationCoordinate2D]()
    }

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        guard elementName == "trkpt" || elementName == "wpt" else { return }
        guard let latString = attributeDict["lat"], let lonString = attributeDict["lon"] else { return }
        guard let lat = Double(latString), let lon = Double(lonString) else { return }
        guard let latDegrees = CLLocationDegrees(exactly: lat), let lonDegrees = CLLocationDegrees(exactly: lon) else { return }

        coordinates.append(CLLocationCoordinate2D(latitude: latDegrees, longitude: lonDegrees))
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接