简体   繁体   中英

how to retrive location from a PFGeopoint - (Parse.com and Swift) and show it on the map with Xcode 6.2

There are some answer on this, but related to different problems and all in objective-c. I save in a parse class "Position" positions of users with this:

var locationManager = CLLocationManager()

var lat = locationManager.location.coordinate.latitude
var lon = locationManager.location.coordinate.longitude

let myGeoPoint = PFGeoPoint(latitude: lat, longitude:lon)
let myParseId = PFUser.currentUser().objectId //PFUser.currentUser().objectId

println("****** this is my geoPoint: \(myGeoPoint)")

func sendPosition(userOfPosition: User) {

let takePosition = PFObject(className: "Position")

 takePosition.setObject(myParseId, forKey: "who") //who
 takePosition.setObject(myGeoPoint, forKey: "where")
                                        takePosition.saveInBackgroundWithBlock(nil)

                                }


  sendPosition(currentUser()!)

so this is my result: 在此处输入图片说明

then I want to show them on map, but how? don't understand how to retrive latitude and longitude from "where" column the code below doesn't work:

   import UIKit
    import MapKit

    class MapViewController: UIViewController {


    @IBOutlet weak var mapView: MKMapView!

    var locationManager : CLLocationManager!


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.



        var locationManager = CLLocationManager()

        var lat = locationManager.location.coordinate.latitude
        var lon = locationManager.location.coordinate.longitude

        let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)
        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegionMake(location, span)
        mapView.setRegion(region, animated: true)

        let anotation = MKPointAnnotation()
        anotation.setCoordinate(location)
        anotation.title = "my title"
        anotation.subtitle = " my subtitle"

        mapView.addAnnotation(anotation)

        println("****** Welcome in MapViewController")



        //MARK: (471) Crossing Positions
        //*******************************************************

        let myGeoPoint = PFGeoPoint(latitude: lat, longitude:lon)
        let myParseId = PFUser.currentUser().objectId //PFUser.currentUser().objectId

        println("****** this is my geoPoint from map view controller: \(myGeoPoint)")


//        
//        var inspector = PFQuery(className:"GameScore")
//                inspector.saveInBackgroundWithBlock {
//                    (success: Bool, error: NSError?) -> Void in
//                    if (success) {
//                        // The object has been saved.
//                        var the = inspector.objectId
//                    } else {
//                        // There was a problem, check error.description
//                    }
//                }
//        
//        
//        


        func filterByProximity() {
            PFQuery(className: "Position")
                .whereKey("where", nearGeoPoint: myGeoPoint, withinKilometers: 500.0)     //(474)
            .findObjectsInBackgroundWithBlock ({
                objects, error in
                if let proximityArray = objects as? [PFObject] {
                    println("****** here the proximity matches: \(proximityArray)")
                    for near in proximityArray {
                        println("here they are \(near)")
                        if let position = near["where"] as! PFGeoPoint {
                        let theirLat = position.latituide
                        let theirLon = position.longitude
                    }

                        let theirLat = near["where"].latitude as Double
                        let theirlong = near["where"].longitude as Double
                        let location = CLLocationCoordinate2DMake(theirLat, theirlong)
                        let span = MKCoordinateSpanMake(0.05, 0.05)
                        let region = MKCoordinateRegionMake(location, span)
                        self.mapView.setRegion(region, animated: true)
                        let theirAnotation = MKPointAnnotation()
                        theirAnotation.setCoordinate(location)
                        self.mapView.addAnnotation(anotation)

                    }
                }
            })
        }

        filterByProximity()


//        //update my position
//        
//        func exists() {
//        PFQuery(className:"Position")
//            .whereKey("who", containsString: myParseId)
//            .findObjectsInBackgroundWithBlock({
//            thisObject, error in
//                if let result = thisObject as? [PFObject] {
//                    println("here the result: \(result)")
//                    
//                    let gotTheId = result[0].objectId
//                    println("ecco l'id singolo \(gotTheId)")
//
//                            //******** update function ********
//                            var query = PFQuery(className:"Position")
//                            query.getObjectInBackgroundWithId(gotTheId) {
//                                (usingObject: PFObject?, error: NSError?) -> Void in
//                                if error != nil {
//                                    println(error)
//                                } else if let objectToupdate = usingObject {
//                                    println("else occurred")
//                                    objectToupdate["where"] = myGeoPoint
//                                    println("position should be updated")
//                                    objectToupdate.saveInBackgroundWithBlock(nil)
//                                    println("position should be saved")
//
//                                }
//                            }
//                            //******** end update function ********
//                }
//            })
//        }
//        
//        exists()

        //*******************************************************




    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




}

Update after first answers

tried to check for optionals, but have this message: 在此处输入图片说明 after not down casting the double: 在此处输入图片说明在此处输入图片说明

the 'where' is a PFGeoPoint, you can just call latitude and longitude on them

Try something like this - I'm not 100% sure in Swift syntax, yet

if(geoPoint)
{
   if(geoPoint!.latitude)
   {
       let latitude = geoPoint!.latitude as double;
   }

}

this worked. Was both a matter of optionals, and a matter of variables, I was using the wrong ones:

        //MARK: (471) Crossing Positions
        //*******************************************************

        let myGeoPoint = PFGeoPoint(latitude: lat, longitude:lon)
        let myParseId = PFUser.currentUser().objectId //PFUser.currentUser().objectId
        var radius = 100.0

        println("****** this is my geoPoint from map view controller: \(myGeoPoint)")


        //MARK: *** let's look for other users ***

        var nearArray : [CLLocationCoordinate2D] = []

        func filterByProximity() {
            PFQuery(className: "Position")
                .whereKey("where", nearGeoPoint: myGeoPoint, withinKilometers: radius)     //(474)
                .findObjectsInBackgroundWithBlock ({
                    objects, error in
                    if let proximityArray = objects as? [PFObject] {
//                        println("****** here the proximity matches: \(proximityArray)")
                        for near in proximityArray {
//                            println("here they are \(near)")

                            let position = near["where"] as? PFGeoPoint

                            var theirLat = position?.latitude       //this is an optional
                            var theirLong = position?.longitude     //this is an optional
                            var theirLocation = CLLocationCoordinate2D(latitude: theirLat!, longitude: theirLong!)

                            nearArray.append(theirLocation)

                            if nearArray.isEmpty {
                                println("*** ERROR! anyone close by ***")
                            } else
                            {
                                for person in nearArray {

                                    let span = MKCoordinateSpanMake(2.50, 2.50)
                                    let region = MKCoordinateRegionMake(theirLocation, span)
                                    self.mapView.setRegion(region, animated: true)

                                    let theirAnotation = MKPointAnnotation()
                                    theirAnotation.setCoordinate(theirLocation)
                                    theirAnotation.title = near["who"] as String

                                    self.mapView.addAnnotation(theirAnotation)
                                }

                            }



                        }
                        println("****** in a radius of \(radius) there are \(nearArray.count) bikers ******")

                    }
                })
        }

        filterByProximity()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM