mysql 按距离(纬度,经度)排序列表

kkbh8khc  于 2023-02-11  发布在  Mysql
关注(0)|答案(1)|浏览(135)

我有这个代码工作100%,计算两个对象之间的距离

public double CalculateDistance(string storelocator_id, BO_MAGASIN magasin)
{
  double response = 0;
  var getMagasin = _context.Magasin.FirstOrDefault(x => x.storelocator_id.Equals(storelocator_id));
  double distance = 0;
  var myMagasin = _context.Magasin.FirstOrDefault(x => x.storelocator_id.Equals("1"));
  string sql;

  var magasins = _context.Magasin.ToList();
  if (storelocator_id != null)
  {
    string latitude = getMagasin.latitude;
    string longitude = getMagasin.longitude;
    string magasin_latitude = magasin.latitude;
    string magasin_longitude = magasin.longitude;
    sql = "set @pt1= point(" + latitude + "," + longitude + ");  set @pt2= point(" + magasin_latitude + "," + magasin_longitude + "); SELECT ST_Distance_Sphere(@pt1, @pt2)/1000";
    try
    {
      MySqlDataReader reader = null;
      string selectCmd = sql;
      string dbConn = configuration.GetSection("ConnectionStrings").GetSection("Default").Value;
      var conn = new MySqlConnection(dbConn);
      conn.Open();

      MySqlCommand command = new MySqlCommand(selectCmd, conn);
      reader = command.ExecuteReader();
      if (reader.Read())
      {
        response = double.Parse(reader[0].ToString());
        if (distance > response)
        {
          distance = response;
        }
      }
      conn.Close();
    }
    catch (Exception ex)
    {

    }   
}
  return distance;
}

我有其他代码返回BO_MAGASIN的列表,但现在我想按距离排序此列表,任何人都知道我如何才能做到这一点?

0md85ypi

0md85ypi1#

您可以使用以下函数在C#中计算这些点之间的距离(使用spherical triangles计算距离)

public double GetDistanceInMeters(BO_MAGASIN entry, BO_MAGASIN other)
    {
        const double earthRadius = 6371.009; // [km]
        const double radian = Math.PI / 180;

        var thisLatitude = entry.latitude;
        var otherLatitude = other.latitude;
        var thisLongitude = entry.longitude;
        var otherLongitude = other.longitude;

        var deltaLongitude = Math.Abs(thisLongitude - otherLongitude);

        thisLatitude *= radian;
        otherLatitude *= radian;
        deltaLongitude *= radian;

        var factor = Math.Pow(10, -3); //result in meters

        var cos = Math.Cos(deltaLongitude) * Math.Cos(thisLatitude) * Math.Cos(otherLatitude) +
                  Math.Sin(thisLatitude) * Math.Sin(otherLatitude);

        return earthRadius * Math.Acos(cos) / factor;
    }

要按距离对列表排序,请使用Linq .OrderBy()
顺便说一句:如果你想让结果以公里为单位,只需删除factor

相关问题