Solution:
To sort by distance, we need to pass the GEO data in the request context.
Code snippet to set GEO data in request context:
// Get request context
const context = PageController.getContext();
// set co-ordinate from props (which we are getting from Google API from search input box)
const coordinate = { lat: props.location.lat, lon: props.location.lng };
// Call helper function to convert miles to km as our search was based on miles metric for radius filtering.
const distance = `${convertMilesToKM(router?.query?.r as string)}km`;
// set geo filtering
const geoFilter = new FilterGeo('locationcoordinate', distance, coordinate);
// set geo data in request context
context.setGeoLocation(coordinate);
// Run the Search query with Sorting option that uses the GEO attribute
query
.getRequest()
.setSearchFilter(geoFilter)
.setSearchSortCriteria({ name: 'locationdistancesort', order: 'asc' });
context.setGeoLocation(coordinate);
Note: Setting the sorting criteria is important along with GEO data that is in the Request context and sorting name locationdistancesort
in above code is defined as Sorting options
in Sitecore Search portal under Administration > Domain settings
Code snippet to reset GEO data in request context:
Once GEO data is set in request context Sitecore Search will display results sorted by distance from point A to co-ordinates stored on the result item.
context.resetGeoLocation();
Resetting will be useful when same search interface has radio button (or some selection) to switch between location-based search and text-based search
Some reference links:
GEO data is discussed here
GEO datatype is discussed here
Creating sorting option is discussed here
Note: This is not officially documented in Sitecore doc site yet (as of 9/25/2024).