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

时间:2016-07-21 14:41:18

标签: ios swift xcode mkmapview gpx

所以在我提出的other问题中,我发现我可以轻松创建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。

任何帮助都会非常感激,因为我没有在google上找到有关如何使用swift读取gpx文件的任何内容。

提前致谢 -Jorge

2 个答案:

答案 0 :(得分:11)

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

我希望它有助于某人

答案 1 :(得分:0)

快捷方式

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