Guides / Managing results / Refine results / Geo location

Filter results inside a rectangle

In this tutorial, ‘ll see how to can filter results inside a rectangular area. This location can either be set manually or taken from the current user position.

Dataset

The dataset contains 3000+ of the biggest airports in the world.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
 {
    "objectID": "3797",
    "name": "John F Kennedy Intl",
    "city": "New York",
    "country": "United States",
    "iata_code": "JFK",
    "_geoloc": {
      "lat": 40.639751,
      "lng": -73.778925
    },
    "links_count": 911
  }
]

To tell Algolia where each record is located, the latitude and longitude must be stored in the _geoloc attribute.

Initialize the client

  1. Download the data set
  2. Set up an API client and send your data to Algolia

Configure index settings

Even if you just want to sort by distance to a location, your textual relevance should also be good so that users can refine the search with a query. To do that, you must configure the index.

1
2
3
4
5
6
7
8
9
10
11
$index->setSettings({
  'searchableAttributes' => [
    'name',
    'city',
    'country',
    'iata_code'
  ],
  'customRanking': [
    'desc(links_count)'
  ]
});

Searchable attributes

The searchable attributes are: name, city, country, and iata_code.

Custom ranking

Algolia will use an airport’s number of connected airports as a ranking metric. The more connections, the better.

Filtering inside a rectangle area

The USA can be considered as a polygon:

Filter inside rectangle

To filter inside this rectangle, you need to pass the upper-left and bottom-right latitude and longitude to the insideBoundingBox parameter:

  • 49.067996905313834, 65.73828125
  • 25.905859247243498, 128.8046875
1
2
3
4
5
6
7
8
9
10
$boundingBox = [
  49.067996905313834, // p1Lat
  65.73828125, // p1Lng
  25.905859247243498, // p2Lat
  128.8046875 // p2Lng
];

$results = $index->search('', [
  'insideBoundingBox' => [$boundingBox]
]);

The empty query ('') returns all matching airports.

Did you find this page helpful?