How To Get “Near By Me” Location Using Sitecore Search?

Dear Sitecorians, to provide better experience to your website users sometimes you are asked implement a feature such as StoesNearByMe, EventsNearByMe or JobsNearByMe in your Sitecore solution. In such scenarios, basically you need two information: 1) User’s location (e.g latitude and longitude) 2) Search all stores, events or jobs near to user’s location. We have already seen how to get user’s location in one the previous posts. If you haven’t then I would suggest to read that post first. Once you have user’s location handy, then you can pass this information (e.g. latitude and longitude) to below method which will build Sitecore predicate search query to pull near by items.

   // NearByMe | ToDo : impelement predicate for near by public static Expression<Func<NewJobModel, bool>> ContainsNearByMe(Double Latitude, Double Longitude)         {             var predicate = PredicateBuilder.True<NewJobModel>();              //Within 25 Miles (40.2336 KMs)             double distance = 40.2336;              // earth's radius in km = ~6371             double radius = 6371;              // latitude boundaries             double minlat = Latitude - RadianToDegree(distance / radius);             double maxlat = Latitude + RadianToDegree(distance / radius);              // longitude boundaries (longitude gets smaller when latitude increases)                         double minlng = Longitude - RadianToDegree(distance / radius / Math.Cos(DegreeToRadian(Latitude)));             double maxlng = Longitude + RadianToDegree(distance / radius / Math.Cos(DegreeToRadian(Latitude)));              //query = context.GetQueryable<NewJobModel>().Where(builder).Where             predicate = Latitude.ToString().Aggregate(predicate, (current, temp)                  => current.Or((item => (item.Latitude >= minlat && item.Latitude <= maxlat)                               )));              predicate = predicate.And(Longitude.ToString().Aggregate(predicate, (current, temp)                  => current.Or((item => (item.Longitude >= minlng && item.Longitude <= maxlng)                            ))));              return predicate;         }      private static double RadianToDegree(double angle)   {       return angle * (180.0 / Math.PI);   }   

Above algorithm calculates near by location within 25 miles radius, you can change it as per your need. Finally You can call above function using your PredicatBuilder like this:

    var builder = PredicateBuilder.True<newjobmodel>();    //Location near me   if (jobSearchModel.Latitude != 0 &amp;&amp; jobSearchModel.Longitude != 0)   {        builder = builder.And(ContainsNearByMe(jobSearchModel.Latitude, jobSearchModel.Longitude));   } 

This will be gold dust for your Sitecore search implementation.

Leave a Reply