2017-03-15 70 views
-2

我想從我的應用中添加我的位置值,並將它們轉換爲註釋。這是我一分鐘沒有工作的代碼!尋找一個援助之手,感覺就像我非常接近這個權利,但我已經打了一個大腦!Firebase地圖到地圖

import UIKit 
import Firebase 
import MapKit 

class ViewController: UIViewController { 

@IBOutlet weak var mapView: MKMapView! 

let locationsRef = FIRDatabase.database().reference(withPath: "locations") 


override func viewDidLoad() { 
    super.viewDidLoad() 
    locationsRef.observe(.value, with: { snapshot in 
     for item in snapshot.children { 
      guard let locationData = item as? FIRDataSnapshot else { continue } 
      let locationValue = locationData.value as! [String: Any] 

      let location = CLLocationCoordinate2D(latitude: locationValue["lat"] as! Double, longitude: locationValue["lng"] as! Double) 
      let name = locationValue["name"] as! String 
      self.addAnnotation(at: location, name: name) 


     } 
    }) 
} 



func addAnnotation(at location: CLLocationCoordinate2D, name: String) { 

    // add that annotation to the map 

     let annotation = MKPointAnnotation() 

     annotation.title = location["name"] as? String 

     annotation.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! Double, longitude: location["lonitude"] as! Double) 

     mapView.addAnnotation(annotation) 



} 


} 

我的代碼是現在的工作,但我得到這個問題:

Could not cast value of type "NSTaggedPointerString' (0x10a708d10) to 'NSNumber' (0x109d10488). 

與這行代碼:

let location = CLLocationCoordinate2D(latitude: locationValue["lat"] as! Double, longitude: locationValue["lng"] as! Double) 

我讀過一些有關將字符串轉換成翻倍但是這行中沒有字符串?任何人都可以幫忙嗎?

更新的代碼字幕

Subtitle

更新錯誤

Error

+1

請解釋 「不工作」,包括樣本你的JSON數據。 –

+0

你在這裏工作太辛苦 - 在你的方法'addAnnotation'中,你再也沒有字典了,你已經有了一個位置和一個名字 - 只需要使用這些變量 – Russell

回答

0

你最有可能存儲座標在火力地堡數據庫String對象。這是導致該錯誤的最常見原因。在這種情況下,請嘗試以下

let lat = Double(locationValue["lat"] as! String) 
let lng = Double(locationValue["lng"] as! String) 
let location = CLLocationCoordinate2D(latitude: lat, longitude: lng) 

更新

數據庫的一些位置條目存儲爲String對象,其他如浮點數。你應該有一個一致的結構(即它們都是字符串或雙打)。 無論哪種方式,這裏是你的錯誤的解決方案:

var location: CLLocationCoordinate2D! 

if let lat = locationValue["lat"] as? String { 
    // stored as String 
    let lng = Double(locationValue["lng"] as! String)! 
    location = CLLocationCoordinate2D(latitude: Double(lat)!, longitude: lng) 
} 
else { 
    // stored as a floating point number 
    let lat = locationValue["lat"] as! Double 
    let lng = locationValue["lng"] as! Double 
    location = CLLocationCoordinate2D(latitude: lat, longitude: lng) 
} 

EDIT 2

只需卸下let這裏

Error line

+0

你能指出我的方向嗎?能夠顯示和隱藏取決於其副標題的註釋。我想我需要創建一個有「全部」,「滑板場」和「街頭滑冰」三個選項的桌面視圖。當我點擊某個視圖時,只顯示這些註釋 – Cal