2016-09-25 4 views
0

Ich arbeite derzeit an einem Projekt. Ich möchte die Koordinaten in meiner Firebase-Datenbank auf der Karte anzeigen. Sie können meinen Code unten sehen.Holen Sie sich Standort von Firebase und zeigen Sie es auf der Karte

Ich bin ziemlich neu in Xcode und Swift. Ich weiß nicht, wie ich die Daten von Firebase abrufen und in der Karte implementieren kann. Sie können sehen, dass ich (im unteren Teil des Codes) den Ort notiere, an dem die Koordinaten implementiert werden (denke ich?).

Hier ist meine Firebase Datenbank:

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() 



} 


} 

Antwort

0

Für die Koordinaten des aktuellen Benutzers abzurufen, verwenden Sie diese: -

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) 
     } 
    }) 
+0

Hallo, danke für die Antwort, ich bin mit dem Swift 2 "Version" verwenden. Ich bin nicht 100% sicher, wo der Code implementiert werden soll. Ich habe es in der Funktion "func locationManager (Manager: CLLocationManager, didUpdateLocations locations: [CLLocation])" implementiert und bekomme folgende Fehlermeldung: Wert vom Typ "FIRDatabaseQuery" hat kein Mitglied "queryEqualtovalue" – Stevic

+0

Ich habe den Code jetzt aktualisiert, wie geht es Ihnen bedeuten mit: "und dann im Abschlussblock das Zentrum und die Region"? – Stevic

+0

Okay, jetzt sehe ich es. Die App läuft, aber ich bekomme das in der Konsole: Mit einem nicht angegebenen Index. Erwägen Sie ".Index": "fromId" bei/Position zu Ihren Sicherheitsregeln für eine bessere Leistung und kann die Position nicht sehen – Stevic

Verwandte Themen