Message:

Subscribe rss
Blog categories
All | Backendless features
Feature 103: Search data objects by distance from a location
April 22, 2015 by markpiller
Spread the love

In my previous posts I described how a data object may have a related geopoint (or a collection of). One of the benefits of the data-to-geo relationships is search by distance. That means Backendless can search for data objects using the location of the related geopoints. Consider an example from a taxi-reservation system. There may be several cabs-for-hire in the area. Your app needs to locate all available cars within the specified distance from where the customer is located.

The class representing a cab may look like this:

Notice the class has the location field of type  GeoPoint. The related GeoPoint object represents the current location of the car.

To search for all available cars within distance from a location (which is the place where the customer who needs to get a car is located), Backendless provides a special function which can be used in the SQL queries. The following SQL where clause can be used in Backendless to find all available cars located within 10 miles from the specified coordinates (32.803, -96.770 – near Dallas, Texas downtown):

The query when sent to the Car  table should be read in plain English as: “locate all available cars for which the location.latitude and location.longitude coordinates are located within 5 miles from the point at 32.803, -96.770.

Notice the location.latitude  and location.longitude arguments. The “location” part refers to the location field of the Car class shown above. The “latitude” and “longitude” parts refer to the properties of the GeoPoint class identified by the location field. The  mi(5) operator is used by the distance function and indicates the distance of 5 miles.

The code to setup some sample data is:

The sample code below demonstrates the query in action:

Asynchronous API sample (Android and Plain Java):

Synchronous API sample (Plain Java only):

Program output:

 

Share this post
Tweet about this on TwitterShare on FacebookGoogle+
  • allo86

    For a search in kilometers, what function can I use insted of mi()?

    • Mark Piller

      Use km( x ). See the doc at the link below (search for “Find objects within certain distance from a geo point here” ):
      http://backendless.com/documentation/data/android/data_search_and_query.htm

      • allo86

        Thanks @markpiller:disqus. And is it possible to get the related objects sorted by distance?

        • Mark Piller

          They are automatically sorted by distance

          • allo86

            I have tested with different origin geopoints, and I always get the results in the same order.

          • Mark Piller

            Please post the problem to the support forum (http://support.backendless.com) with sample code.