Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whereNear query doesn't seem to work properly in Parse

I'm working on an Android app related to Geolocations. I'm using Parse as backend. I need to display results based on user's current location.

I'm using this query:

ParseQuery<ParseObject> query = ParseQuery.getQuery("Restaurants"); 
ParseGeoPoint sLatlong = new ParseGeoPoint(currentLat, currentLong);
        query.whereNear("rest_location", sLatlong);  

But the results are not sorted distance wise.

Can someone help me out.

like image 317
Anirudh Avatar asked Feb 01 '16 05:02

Anirudh


1 Answers

According to the Android Documentation for Parse the default sort order should already be by distance (nearest to farthest) unless you are specifying another sort order yourself.

Also, you might want to look into the ParseQuery.whereWithin* methods as you can specify you only want locations within a certain number of miles, kilometers, etc.

If all else fails and the sort order just doesn't want to work on the returned locations you can always sort them yourself by looping through the ParseObjects returned from the query and using ParseObject.getParseGeoPoint("rest_location").

That will return a ParseGeoPoint object and you can then do the following

ParseGeoPoint.distanceInKilometersTo(sLatlong);

To get the distance to the user's location and sort on that.

For reference here is a sample Comparator:

public class UserLocationComparator  implements Comparator<ParseObject> {

    private final ParseGeoPoint userLoc;

    public UserLocationComparator(ParseGeoPoint userLoc) {
        this.userLoc = userLoc;
    }

    @Override
    public int compare(ParseObject po1, ParseObject po2) {
        ParseGeoPoint loc1 = po1.getParseGeoPoint("rest_location");
        ParseGeoPoint loc2 = po2.getParseGeoPoint("rest_location");

        return loc1 == null ?
                (loc2 == null ? 0 : 1) :
                (loc2 == null ? -1 : Double.compare(userLoc.distanceInKilometersTo(loc1), userLoc.distanceInKilometersTo(loc2)));
    }
}

and then assuming you have a List<ParseObject> results; simply do:

Collections.sort(results, new UserLocationComparator(sLatlong));
like image 172
George Mulligan Avatar answered Nov 05 '22 07:11

George Mulligan