我不会使用withinKilometers
. 相反,我会使用该withinMiles
方法。在 Swift 中使用 Parse 中的地理点要容易得多。如果您仍想使用公里,只需将公里转换为英里。在这种情况下,而不是:
withinKilometers: 1.0
利用:
withinMiles: 0.62
下面的代码应该可以工作:
query.whereKey("Name", nearGeoPoint: geoPoint, withinMiles: 0.62)
如果上面的代码不起作用:
试试这个,这是我用来在距离用户当前位置几英里的地图上显示点的编码。但是你必须在 info.plist 文件中设置一些东西来获取用户的当前位置。这是您可以尝试的示例代码。
import UIKit
import MapKit
import CoreLocation
import Parse
import ParseUI
import Bolts
var currentLoc: PFGeoPoint = PFGeoPoint()
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var query: PFQuery = PFQuery()
var manager:CLLocationManager!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
query = PFQuery(className: "ClassName")
query.whereKey("dateOfClass", greaterThanOrEqualTo: NSDate())
query.whereKey("classes", nearGeoPoint: currentLoc, withinMiles: 400)
query.findObjectsInBackgroundWithBlock {
(posts, error) -> Void in
if error == nil {
let myPosts = posts as! [PFObject]
for post in myPosts {
var subtitleString: String = String()
if let dateObject = post["dateOfClass"] as? NSDate {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm a"
var dateNSDate: String = dateFormatter.stringFromDate(dateObject)
subtitleString = dateNSDate
}
let point = post["classes"] as! PFGeoPoint
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: point.latitude, longitude: point.longitude)
var workoutClassName: String = post.objectForKey("workoutClassName") as! String
var workoutClassInstructor: String = post.objectForKey("instructorName") as! String
var objectsID: String = post.objectId! as String
var annotation: MapPin = MapPin(coordinate: coordinate, title: "\(workoutClassName), \(workoutClassInstructor)", subtitle: "\(subtitleString)", annotationID: "\(objectsID)")
self.mapView.addAnnotation(annotation)
}
} else {
// Log details of the failure
println("Error: \(error)")
}
}
println(currentLoc)
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.showsUserLocation = true
var latitude: CLLocationDegrees = currentLoc.latitude
var longitude: CLLocationDegrees = currentLoc.longitude
var latDelta:CLLocationDegrees = 0.7
var lonDelta:CLLocationDegrees = 0.7
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: false)
}
}