如何将String转换为CLLocationDegrees Swift 2

时间:2016-08-12 16:06:01

标签: ios swift firebase firebase-realtime-database

我正在尝试转换我从Firebase检索的字符串,并将其作为多个注释添加到Google地图上。不幸的是,无论何时通过当前代码,我的应用程序都会崩溃:

ref = FIRDatabase.database().reference()
    ref.child("Locations").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
        let lat = (snapshot.value!["Latitude"] as! NSString).doubleValue
        let lon = (snapshot.value!["Longitude"] as! NSString).doubleValue



        let complainLoc = CLLocationCoordinate2DMake(lat, lon)

        let Coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lon)

    })

My JSON Tree

My Code Block Which Crashes

以下是我用于将数据保存到Firebase的代码

FIRDatabase.database().reference().child("Location").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Latitude": locationManager.location!.coordinate.latitude, "Longitude": locationManager.location!.coordinate.longitude])

2 个答案:

答案 0 :(得分:3)

确保将latlon的值保存到数据库时将其保存为Float或Double .. 检索用途:

ref = FIRDatabase.database().reference()
    ref.child("Locations").observeEventType(.Value, withBlock: { (snapshot) in

   if snapshot.exists(){       

    if let locationDictionary = snapshot.value as [String : AnyObject]{

      for each in locationDictionary{          

     //each will bring you every location dictionary in your database for your every user
             let lat = each.value!["Latitude"] as! CLLocationDegrees
             let lon = each.value!["Longitude"] as! CLLocationDegrees
             let userId = each.key as! String

             let complainLoc = CLLocationCoordinate2DMake(lat, lon)

             let Coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lon)   
       //Every time this for loop complete's itself it will generate a new set of Coordinates for each user   
        }
      }
   }
})

答案 1 :(得分:0)

SWIFT 5

let dbLat = Double(latStr)  // Convert String to double
let dbLong = Double(longStr)

使用经纬度

let center = CLLocationCoordinate2D(latitude: dbLat! , longitude: dbLong! )

let pointAnnotation = MKPointAnnotation()
 pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: dbLat!, longitude:dbLong!)