如何将字符串转换为 CLLocationDegrees Swift 2

Ish*_*ain 4 ios firebase swift 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)

    })
Run Code Online (Sandbox Code Playgroud)

我的 JSON 树

我的代码块崩溃了

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

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

小智 7

环球银行金融电信协会5

let dbLat = Double(latStr)  // Convert String to double
let dbLong = Double(longStr)
Run Code Online (Sandbox Code Playgroud)

使用纬度和经度

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

let pointAnnotation = MKPointAnnotation()
 pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: dbLat!, longitude:dbLong!)
Run Code Online (Sandbox Code Playgroud)


Dra*_*ian 5

确保当您将lat和的值保存lon到数据库时,您将它们保存为浮点数或双精度.. 检索使用:

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   
        }
      }
   }
})
Run Code Online (Sandbox Code Playgroud)

编辑:

更新了 Firebase 6 和 Swift 5 的代码

let ref = self.ref.child("Locations")
ref.observeSingleEvent(of: .value, with: { snapshot in
    let allLocations = snapshot.children.allObjects as! [DataSnapshot]
    for location in allLocations {
        let lat = location.childSnapshot(forPath: "Latitude").value as! CLLocationDegrees
        let lon = location.childSnapshot(forPath: "Longitude").value as! CLLocationDegrees
        let userId = location.key
        let locCoord = CLLocationCoordinate2DMake(lat, lon)
        let coordinates  = CLLocationCoordinate2D(latitude: lat, longitude: lon)
    }
})
Run Code Online (Sandbox Code Playgroud)

请注意 self.ref 指向我的 Firebase 根引用。