簡體   English   中英

在地圖解析中顯示所有用戶的地理位置

[英]Displaying geopoint of all users in a map parse

我試圖查詢存儲在Parse后端的PFGeoPoints數組。 我有User表,並為其分配了數據,例如“location”,“name”。 從我的應用程序發布后,所有內容都被發送到Parse並正確存儲在后端。 我在從Parse檢索所有位置並將它們存儲到地圖上的MKAnnotation時遇到問題。 在下面找到我的代碼

 import UIKit import Parse import CoreLocation import MapKit class mapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet var mapUsers: MKMapView! var MapViewLocationManager:CLLocationManager! = CLLocationManager() var currentLoc: PFGeoPoint! = PFGeoPoint() override func viewDidLoad() { super.viewDidLoad() // ask user for their position in the map PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if let geoPoint = geoPoint { PFUser.currentUser()? ["location"] = geoPoint PFUser.currentUser()?.save() } } mapUsers.showsUserLocation = true mapUsers.delegate = self MapViewLocationManager.delegate = self MapViewLocationManager.startUpdatingLocation() mapUsers.setUserTrackingMode(MKUserTrackingMode.Follow, animated: false) } override func viewDidAppear(animated: Bool) { let annotationQuery = PFQuery(className: "User") currentLoc = PFGeoPoint(location: MapViewLocationManager.location) annotationQuery.whereKey("Location", nearGeoPoint: currentLoc, withinMiles: 10) annotationQuery.findObjectsInBackgroundWithBlock { (PFUser, error) -> Void in if error == nil { // The find succeeded. print("Successful query for annotations") let myUsers = PFUser as! [PFObject] for users in myUsers { let point = users["Location"] as! PFGeoPoint let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude) self.mapUsers.addAnnotation(annotation) } } else { // Log details of the failure print("Error: \\(error)") } } } 

而不是將調用放在你的viewDidAppear()方法中 - 正如之前的評論者所說,你的位置可能是零,沒有返回任何結果 - 我會使用某種跟蹤器並將它放在你的didUpdateLocations() MKMapView委托方法中。 在這里,我使用GCD的dispatch_once()這樣當我第一次以合理的准確度找到我的位置時,我的代碼就被執行了(這里你將調用Parse)。

聲明GCD的跟蹤變量

var foundLocation: dispatch_once_t = 0

現在在您的位置管理器的委托方法中使用類似的東西didUpdateLocations()

    if userLocation?.location?.horizontalAccuracy < 2001 {
        dispatch_once(&foundLocation, {
            // Put your call to Parse here
        })
    }

PS。 您還應該考慮在主線程上對UI進行任何更新。 Parse在后台線程上獲取數據,雖然您可能永遠不會看到問題,但在主線程上進行任何UI更改都是更安全和更好的習慣。 您可以使用以下內容執行此操作:

dispatch_async(dispatch_get_main_queue(), {
    // Put any UI update code here. For example your pin adding
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM