Using GeoPoint with Swift

In this guide, we will show how work with the Parse GeoPoint object in Swift to make an app with location access.

Simple app using Parse GeoPoint: Github


Enable Location in your app:

  1. Open your app’s Info.plist and add a key named NSLocationAlwaysUsageDescription with a string as value, this string should tell why your app need the location access.captura-de-tela-2016-10-17-as-00-08-51


Get Device GeoPoint:

  1. To create a new Parse GeoPoint, we use a PFGeoPoint object:
    let geoPoint = PFGeoPoint(latitude: -16.22005, longitude: -58.54621)
  2. Lets now get the curernt location of the device. FOr this, we just need to use the geoPointForCurrentLocationInBackground method:
    PFGeoPoint.geoPointForCurrentLocationInBackground {(geopoint, error) in
        if error == nil {
            // Make stuff with geopoint (it’s the current location of the device)
        } else {
            // Handle with the error

Upload the GeoPoint to back4app:

To upload an geopoint to back4app, we make a field of an PFObject receive the PFGeoPoint. In the following example, we will make a new object of the class “Contact” and will place the GeoPoint in the “location” field:

let contact = PFObject(classname: “Contact”)
let geoPoint = PFGeoPoint(latitude: -18.2043, longitude: -40.2323)
contact[“location”] = geoPoint

Query Nearest GeoPoints:

To make a query, we must use the PFQuery object, then using the whereKey with nearGeoPoint argument. To find the objects, we use the findObjectsInBackgroundWithBlock, with gives the results of the query:

let query = PFQuery(className: “className”)
query.whereKey(“geoPointColumnName”, nearGeoPoint: geopoint)
query.findObjectsInBackgroundWithBlock {(results, error) -> Void in
    // Do something with results

Query Nearest GeoPoints within Area:

To fetch only objects in a certain distance from a GeoPoint, we need to add an argument to the whereKey method. This argument will depend on the unit used, if we want to use miles, add the withinMiles, for kilometers, add withinKilometers. In the following example, we fetch the objects in the “Contacts” class, GeoPoints in “location” column, within a distance of 5 kilometers:

let query = PFQuery(className: “Contacts”)
query.whereKey(“location”, nearGeoPoint: currentLocation, withinKilometers: 5)
query.findObjectsInBackgroundWithBlock {(results, error) -> Void in
    if !error {

Get Distance between two GeoPoints:

Sometimes we want to know the distance between two points. This can be done using some PFGeoPoint’s methods. For distance in miles, use distanceInMilesTo, and for a distance in kilometers, distanceInKilometersTo. See the code below:

let geoPoint = PFGeoPoint(latitude: -16, longitude: 40)
let otherGeoPoint = PFGeoPoint(latitude: -18, longitude: 43)
var distance = geoPoint.distanceInKilometersTo(otherGeoPoint)