Skip to content

Nearby using FrontQL

FrontQL’s nearby feature allows you to calculate distances between geographical coordinates and find records within a specific proximity. It calculates the distance from a given latitude/longitude to target coordinates stored in your database and returns the distance in kilometers.

How it Works

  • Calculates the distance from the given lat/lng to the targeted lat/lng (which is stored in the database) in KM
  • Returns the distance in KM along with the query results

Usage

To use the nearby feature, you need to specify coordinates in two places:

1. Headers - Database Field Names

Specify which fields in your database contain the latitude and longitude coordinates:

nearby: <latitude_field_name>,<longitude_field_name>

Example:

nearby: latitude,longitude

or

nearby: store_lat,store_lng

2. Query Parameters - Reference Point

Provide the coordinates from which you want to calculate distances:

nearby: <your_latitude>,<your_longitude>

Example:

nearby: 40.7128,-74.0060

Complete Request Format

GET /api/restaurants?nearby=40.7128,-74.0060
Headers:
Content-Type: application/json
nearby: latitude,longitude

JavaScript Usage Example

// Example: Find nearby restaurants
const findNearbyRestaurants = async () => {
try {
const response = await fetch(`${BASE_URL}/restaurants`, {
method: "GET",
headers: {
"Content-Type": "application/json",
// Specify the database field names for latitude and longitude
nearby: "latitude,longitude",
},
// URL parameters with your current location
params: new URLSearchParams({
// Your current coordinates (from which to calculate distance)
nearby: "40.7128,-74.0060",
}),
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching nearby restaurants:", error);
}
};

Response Format

The response will include the original data plus a nearby field showing the calculated distance in kilometers:

[
{
id: 1,
name: "Restaurant A",
latitude: 40.7589,
longitude: -73.9851,
nearby: 2.3, // Distance in KM
},
{
id: 2,
name: "Restaurant B",
latitude: 40.7505,
longitude: -73.9934,
nearby: 3.7, // Distance in KM
},
];

Use Cases

  • Store Locators: Find the nearest stores to a customer’s location
  • Real Estate: Find properties near specific locations
  • Social Networks: Show nearby users or events
  • Transportation: Find nearest pickup points or stations

Notes

  • Coordinates should be provided in decimal degrees format
  • The distance calculation is accurate for most practical applications
  • Results can be combined with other FrontQL features like filtering and sorting
  • Consider adding appropriate database indexes on latitude/longitude fields for better performance