2015-07-20 77 views
-1

我試圖實現一種使用Google對齊道路API的方法,但是我一直無法實現任何結果。在Swift中捕捉道路

我能夠使用

https://maps.googleapis.com/maps/api/directions/json?origin=xyz 

let request = NSURLRequest(URL: NSURL(string:directionURL)!) 
    let session = NSURLSession.sharedSession() 
    session.dataTaskWithRequest(request, 
     completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) in 

      if error == nil { 
       let object = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary 
       println(object) 

       let routes = object["routes"] as! [NSDictionary] 
       for route in routes { 
        println(route["summary"]) 
       } 
       dispatch_async(dispatch_get_main_queue()) { 
        //update your UI here 
       } 
      } 
      else { 
       println("Direction API error") 
      } 

    }).resume() 

但是,如果GPS座標,甚至略有不同,我得到一個完全不同的結果,成功地實現了方向API在我的雨燕項目。

我想要做的是每次都繪製一條用戶路徑,即使開始/結束座標略有不同。

我得到的錯誤是

fatal error: unexpectedly found nil while unwrapping an Optional value 

有什麼建議?

感謝

編輯:

我想這一點,但,這是什麼原因造成的錯誤

func directionAPITest() { 

    let directionURL = "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907|-35.28099,149.12929|-35.28144,149.12984|-35.28194,149.13003|-35.28282,149.12956|-35.28302,149.12881|-35.28473,149.12836&interpolate=true&key=xyz" 

    let request = NSURLRequest(URL: NSURL(string:directionURL)!) 
    let session = NSURLSession.sharedSession() 

} 
+0

你確定JSONObjectWithData是一個NSDictionary嗎? (而不是一個數組)你可以添加一個斷點到該行並檢查數據,而不使用顯式轉換。這些數據也是零? – Konrad77

+0

您是否遇到崩潰或「完全不同的結果」?請更清楚地解釋你的問題。 – Mundi

+0

是的,我正在崩潰。我添加了錯誤。我只是想能夠成爲道路api,而不是方向api – puks1978

回答