2017-09-18 1 views
1

Je reçois mes coordonnées de Firebase et ensuite je les mets sur ma carte, mais le problème est que mon instruction d'extraction de Firebase arrive après que la map ait initialisé les marqueurs, donnant nil dans mes coordonnées.Comment obtenir la valeur de la fonction après son initialisation?

Comment puis-je obtenir les valeurs de Firebase et les mettre en tant que marqueur?

var fetchLat: Double! 
var fetchLong: Double! 

Ici, je reçois les valeurs de Firebase

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
{ 
    let camera = GMSCameraPosition.camera(withLatitude: latPass, longitude: longPass, zoom: 5) 
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) 
    view = mapView 
    mapView.settings.scrollGestures = true 
    mapView.settings.zoomGestures = true 
    mapView.settings.myLocationButton = true 

    let dataBaseRef=FIRDatabase.database().reference() 
    dataBaseRef.child("LocationTest").queryOrderedByKey().observe(.childAdded, with: {(snapshot) in 

     let postDict = snapshot.value as? [String : AnyObject] ?? [:] 
     var fetchLat = postDict["lat"] as! Double 
     var fetchLong = postDict["long"] as! Double 
}) 

Ici, je les mets sur la carte

let friendLocator = [ 
     Locator(name: "Virat", long: fetchLong, lat: fetchLat), 
    ] 

    for friend in friendLocator{ 

     let friendMarker = GMSMarker() 
     friendMarker.position=CLLocationCoordinate2D(latitude: friend.lat, longitude: friend.long) 
     friendMarker.title=friend.name 
     friendMarker.map=mapView 
     mapView.selectedMarker=friendMarker 
    } 

Parce que l'initialisation de la carte est faite avant que les valeurs sont extraites de Firebase, comment puis-je définir les marqueurs après que les valeurs soient récupérées?

+0

pourquoi vous appelez firebase FETCH à l'intérieur didUpdateLocations. – Pushpendra

+0

@Pushpendra parce que j'ajoute mes marqueurs dans 'didUpdateLocations' –

+0

@ naveen-saini: view = mapView Quelle est la vue là-bas? Self.view ou une variable UIView séparée appelée view ?? –

Répondre

1

Si le ViewController qui montre l'utilisateur sur la carte est le même que le délégué de LocationManager puis,

Créer une propriété dans votre ViewController,

var friendLocator : [Locator] = [Locator]() 

Créer une fonction pour dessiner l'utilisateur sur la carte

func locateFriends() { 
     if self.view is GMSMapView { 
      for friend in friendLocator { 
       let friendMarker = GMSMarker() 
       friendMarker.position=CLLocationCoordinate2D(latitude: friend.lat, longitude: friend.long) 
       friendMarker.title=friend.name 
       friendMarker.map= (self.view as! GMSMapView) 
       (self.view as! GMSMapView).selectedMarker=friendMarker 
      } 
     } 
    } 

Enfin ajouter par exemple localisateur nouvellement trouvé tableau dans didUpdateLocations délégué

extension ViewController : UIPageViewControllerDelegate { 
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
    { 

     let dataBaseRef=FIRDatabase.database().reference() 
     dataBaseRef.child("LocationTest").queryOrderedByKey().observe(.childAdded, with: {(snapshot) in 

      let postDict = snapshot.value as? [String : AnyObject] ?? [:] 
      var fetchLat = postDict["lat"] as! Double 
      var fetchLong = postDict["long"] as! Double 

      let locator = Locator(name: "Virat", long: fetchLong, lat: fetchLat) 
      //do some sort of duplicate check before blindly adding new locator to array 
      self.friendLocator.append(locator) 
      self.locateFriends() 
     }) 
    } 
} 

Si ViewController qui montre l'utilisateur sur la carte est différente de celle qui est délégué UILocationManager utilise la même logique, mais plutôt utiliser modèle delegate pour informer le ViewController de nouvel objet de localisation et de recharger la carte.

EDIT:

reformatage code OP

import MapKit 

import UIKit 

import CoreLocation 

import GoogleMaps 

import GooglePlaces 

import GoogleMapsCore 

import Firebase 

import FirebaseDatabase 


struct postStruct{ 

    let lat: Double! 

    let long: Double! 

} 


class ViewController: UIViewController,MKMapViewDelegate, CLLocationManagerDelegate, UISearchBarDelegate{ 


    var viratPin=CustomPointAnnotation() 

    var posts=[postStruct]() 
    var mapView : GMSMapView? = nil 


    var friendLocator : [Locator] = [Locator]() 



    @IBOutlet weak var searchBar: UISearchBar! 

    @IBOutlet weak var searchSupporter: UIView! 

    @IBAction func dismissKeyboard(_ sender: Any) { 

     searchBar.resignFirstResponder() 

    } 



    struct Locator { 

     let name: String 

     let long: CLLocationDegrees 

     let lat: CLLocationDegrees 

    } 



    class CustomPointAnnotation: MKPointAnnotation { 

     var imageName: String! 

    } 



    let manager = CLLocationManager() 

    var myLocation: CLLocationCoordinate2D? 

    var friend1: CLLocationCoordinate2D? 

    var arbokPin = CustomPointAnnotation() 

    var location=0 

    var latPass: Double! 

    var longPass: Double! 

    var fetchLat: Double! 

    var fetchLong: Double! 



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

    { 

     var location=locations[0] 

     let span:MKCoordinateSpan=MKCoordinateSpanMake(0.01, 0.01) 

     var myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) 

     let region:MKCoordinateRegion=MKCoordinateRegionMake(myLocation, span) 

     latPass=location.coordinate.latitude 

     longPass=location.coordinate.longitude 


     post() 

     self.configureMapView() 

     let dataBaseRef=FIRDatabase.database().reference() 

     dataBaseRef.child("LocationTest").queryOrderedByKey().observe(.childAdded, with: {(snapshot) in 



      let postDict = snapshot.value as? [String : AnyObject] ?? [:] 

      var fetchLat = postDict["lat"] as! Double 

      var fetchLong = postDict["long"] as! Double 


      let locator = Locator(name: "You", long: fetchLong, lat: fetchLat) 
      self.friendLocator.append(locator) 
      self.locateFriend() 
     }) 

     manager.stopUpdatingLocation() 

     self.view = mapView 
    } 


    func configureMapView() { 
     let camera = GMSCameraPosition.camera(withLatitude: latPass, longitude: longPass, zoom: 5) 

     self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) 

     view = mapView 

     mapView.settings.scrollGestures = true 

     mapView.settings.zoomGestures = true 

     mapView.settings.myLocationButton = true 

     mapView.addSubview(searchBar) 

     mapView.addSubview(searchSupporter) 

     mapView.bringSubview(toFront: searchBar) 


     for gesture in mapView.gestureRecognizers! { 

      mapView.removeGestureRecognizer(gesture) 

     } 
    } 

    func locateFriend() { 
     for friend in friendLocator{ 
      let friendMarker = GMSMarker() 

      friendMarker.position=CLLocationCoordinate2D(latitude: friend.lat, longitude: friend.long) 

      friendMarker.title=friend.name 

      friendMarker.map=mapView 

      mapView.selectedMarker=friendMarker 

      if friend.name=="Virat"{ 

       friendMarker.icon=UIImage(named: "ViratPin.png") 

      } 

      else if friend.name=="Naveen"{ 

       friendMarker.icon=UIImage(named: "naveenPin.png") 

      } 

      else if friend.name=="You"{ 

       friendMarker.icon=UIImage(named: "currentLocation.png") 

      } 

     } 

     do { 

      mapView.mapStyle = try GMSMapStyle(jsonString: kMapStyle) 

     } catch { 

      NSLog("One or more of the map styles failed to load. \(error)") 

     } 
    } 

    override func viewDidLoad() { 

     super.viewDidLoad() 



     manager.delegate=self 

     manager.desiredAccuracy=kCLLocationAccuracyBest 

     manager.requestWhenInUseAuthorization() 

     manager.startUpdatingLocation() 

     searchBar.isUserInteractionEnabled=true 

     searchBar.delegate=self 

     searchSupporter.alpha=0 



    } 





    func searchBarTextDidBeginEditing(_ searchBar : UISearchBar){ 

     self.searchSupporter.alpha=0.8 

     print("yes") 

    } 



    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { 

     searchSupporter.alpha=0 

     print("no") 

    } 



    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 

     print(searchBar.text!) 


    } 


    override var prefersStatusBarHidden: Bool{ 

     return true 

    } 

    func post(){ 

     let post : [String: Double]=["lat":latPass, "long":longPass] 

     let dataBaseRef=FIRDatabase.database().reference() 

     //dataBaseRef.child("Location").childByAutoId().setValue(post) 

     dataBaseRef.child("Location").child("id").setValue(post) 


    } 
} 
+0

mon 'mapView' est initialisé dans' didUpdateLocations', donc, je ne peux pas l'utiliser dans une autre fonction. –

+0

@ naveen-saini: Je ne vois pas de code d'initialisation de la carte dans didUpdateLocations –

+0

@ naveen-saini: Si elle est initialisée dans didUpdateLocations, vous pouvez créer une variable optionnelle pour map et en faire une propriété d'instance de votre ViewController et l'utiliser comme self.mapView dans votre didUpdateLocations et enfin dans la fonction locateFriends avant d'ajouter GMSMarker vérifiez si self.mapView! = nil c'est tout –