从Firebase获取位置并在地图上显示

时间:2016-09-25 18:39:07

标签: ios swift firebase firebase-realtime-database

我目前正在开展一个项目。我想在地图上显示Firebase数据库中的坐标。你可以在下面看到我的代码。

我是Xcode和Swift的新手。我不知道如何从Firebase检索数据并在地图中实现它。你可以看到我评论(在代码的底部)实现坐标的地方(我想?)。

以下是我的Firebase数据库:

import UIKit
import Firebase
import MapKit
import CoreLocation

class ProfileController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

let cellId = "cellId"

var users = [User]()

var positions = [Position]()



override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: #selector(handleLogout))

    navigationItem.title = "Profile"

    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.alwaysBounceVertical = true
    collectionView?.registerClass(FeedCell.self, forCellWithReuseIdentifier: cellId)

    observePosition()

 FIRDatabase.database().reference().child("postion").queryOrderedByChild("fromId").queryEqualToValue(FIRAuth.auth()!.currentUser!.uid).observeSingleEventOfType(.Value, withBlock: {(locationSnap) in

        if let locationDict = locationSnap.value as? [String:AnyObject]{


            let latitude = locationDict["latitude"] as! CLLocationDegrees
            let longitude = locationDict["latitude"] as! CLLocationDegrees

        }
    })




   }

func handleLogout() {

    do {
        try FIRAuth.auth()?.signOut()
    }

 catch let logoutError {
            print(logoutError)
        }

        let loginContoller = LoginController()
        presentViewController(loginContoller, animated: true, completion: nil)

    }


    func observePosition() {

        let ref = FIRDatabase.database().reference().child("position")
        ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let position = Position()
                position.setValuesForKeysWithDictionary(dictionary)
                self.positions.append(position)


                dispatch_async(dispatch_get_main_queue(), {
                    self.collectionView!.reloadData()
                })
            }


            }, withCancelBlock: nil)


    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return positions.count


  }



override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let FedCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! FeedCell

    return FedCell


}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSizeMake(view.frame.width, 450)
}




}

class FeedCell: UICollectionViewCell, UICollectionViewDelegateFlowLayout, CLLocationManagerDelegate, MKMapViewDelegate {

    let users = [User]()

    var positions = [Position]()


var wiindow: UIWindow?
var mapView: MKMapView?
let locationManager = CLLocationManager()

let distanceSpan: Double = 500

var locationData: CLLocation!

override init(frame: CGRect) {
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = "Username"
    label.font = UIFont.boldSystemFontOfSize(14)
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let profileImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.layer.cornerRadius = 22
    imageView.layer.masksToBounds = true
    imageView.backgroundColor = UIColor.blueColor()
    return imageView
}()

let separatorView: UIView = {
    let view = UIView()
    view.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()


func setupViews() {

    addSubview(profileImageView)
    addSubview(nameLabel)
    addSubview(separatorView)


    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[v0(44)]-10-[v1]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profileImageView, "v1": nameLabel]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[v0(44)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profileImageView]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]-385-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": separatorView]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": separatorView]))

    self.wiindow = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.backgroundColor = UIColor(white: 0.95, alpha: 1)

    self.mapView = MKMapView(frame: CGRectMake(0, 70, (self.wiindow?.frame.width)!, 355))
    self.addSubview(self.mapView!)

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
    self.mapView!.showsUserLocation = true

    self.mapView!.zoomEnabled = false
    self.mapView!.scrollEnabled = false
    self.mapView!.userInteractionEnabled = false




}


func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
    if let mapView = self.mapView {
        let region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, self.distanceSpan, self.distanceSpan)
        mapView.setRegion(region, animated: true)
        mapView.showsUserLocation = true
    }
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    locationData = locations.last


    let center = CLLocationCoordinate2D(latitude: //coordinates here, longitude: //coordinates here)

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.mapView!.setRegion(region, animated: true)
    self.locationManager.stopUpdatingLocation()



}


}

1 个答案:

答案 0 :(得分:0)

要检索当前用户的坐标,请使用: -

Swift 3

FIRDatabase.database().reference().child("position").queryOrdered(byChild: "fromId").queryEqual(toValue: FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: {(locationSnap) in

        if let locationDict = locationSnap.value as? [String:AnyObject]{


            let lat = locationDict["latitude"] as! CLLocationDegrees
            let long = locationDict["latitude"] as! CLLocationDegrees
            let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

             self.mapView!.setRegion(region, animated: true)
        }
    })

Swift 2

FIRDatabase.database().reference().child("position").queryOrderedByChild("fromId").queryEqualToValue(FIRAuth.auth()!.currentUser!.uid).observeSingleEventOfType(.Value, withBlock: {(locationSnap) in

        if let locationDict = locationSnap.value as? [String:AnyObject]{


            let lat = locationDict["latitude"] as! CLLocationDegrees
            let long = locationDict["latitude"] as! CLLocationDegrees
            let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

             self.mapView!.setRegion(region, animated: true)
        }
    })