2016-07-21 2 views
1

그래서 내 other 질문에서 내가 쉽게 gpx 파일을 만들 수 있다는 것을 알았지 만 지금은 gpx 파일의 내용을 MKPolygon으로 표시해야합니다. 전에는 plist 파일의 모든 좌표가있는 목록을 만들었습니다. NSDictionary를 만들고 거기에서 읽어서 plist가 제공하는 키를 사용하여 위치를 찾는 것이기 때문에 읽기가 쉬웠습니다. gpx 파일에서이 작업을 쉽게하는 것처럼 보입니다.Swift - gpx 파일에서 좌표를 읽는 방법

나는 GPX 파일의 전체 내용 읽어 코드의이 작은 잘린를 만들었습니다 : 나는 문자열의 전체 텍스트가 이제

if fileManager.fileExistsAtPath(filePath) { 
      let dataBuffer = NSData(contentsOfFile: filePath) 
      let dataString = NSString(data: dataBuffer!, encoding: NSUTF8StringEncoding) 
      print (dataString) 
     } 

을하지만이 모든 필요하지 않습니다 :

나는 위치로 변환하고 거기에서 것은 MKPolygon로 변환 할 수 있습니다
<?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> 태그 사이의 위도와 경도가 필요합니다.

Google에서 신속하게 gpx 파일을 읽는 방법을 찾지 못해 도움을 주시면 대단히 감사하겠습니다. 사전에

감사 -Jorge

답변

3

내가 다음 코드로 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)!)) 
     } 
    } 
} 

나는 희망을 누군가

하는 데 도움이
관련 문제