System.Data.Spatial DbGeography.Distance is not working consistantly

194 Views Asked by At

I am developing an app that needs to calculate the distance between to points. I am using LINQ and the DbGeography class to achieve this.

It is working beautiful in most cases in the app, however I have run into one issue where it does not return the proper result. I please take a look ans see if you spot an issue.

I have hard coded values for testing purposes.

    private void GetUsersByDistance()
    {

        //this code is just for debugging 
        //end this code is just for debugging 


        /// this is the center of town in Santa Cruz
        var lat = decimal.Parse("36.9741171");
        var lng = decimal.Parse("-122.0307963");


        // this is about a 1/4 mile away in Santa Cruz 
        var lat2 = decimal.Parse("36.971524");
        var lng2 = decimal.Parse("-122.0166850");

        var theUsers = new List<PseudoProfile>();

        DbGeography geo = DbGeography.FromText(String.Format("POINT({0} {1})", lng.ToString(CultureInfo.InvariantCulture), lat.ToString(CultureInfo.InvariantCulture)));

        var users =
         (from u in _WebEntities.Users
          select u)
          .AsEnumerable()
          .Where(u => geo.Distance(DbGeography.FromText("POINT(" + lng2.ToString(CultureInfo.InvariantCulture) + " " + lat2.ToString(CultureInfo.InvariantCulture) + ")")) < 100)
          .ToList();
    }

This exact code is working fine with other values, so I am stumped. Please help

Thanks

1

There are 1 best solutions below

0
Sandeep Padarthy On
.Where(u => geo.Distance(DbGeography.FromText("POINT(" + lng2.ToString(CultureInfo.InvariantCulture) + " " + lat2.ToString(CultureInfo.InvariantCulture) + ")")) < 100)

Your filter will return back only locations with a distance less than 100 meters. I have calculated above hard-coded locations and the distance is 1289.0501038954687 meters.

If your intention is getting users within 100 miles, change to below code to convert meters to miles

.Where(u => geo.Distance(DbGeography.FromText("POINT(" + lng2.ToString(CultureInfo.InvariantCulture) + " " + lat2.ToString(CultureInfo.InvariantCulture) + ")")) / 1609.34 < 100)