我有一个位置列表,我希望能够输入一个位置,并将我指定位置 X 英里半径内的位置填充到数据网格中。有没有人有为 C# 编写代码以实现这一目标的经验?
我确实有我的数据的纬度和经度。
任何帮助将不胜感激!谢谢!
我想到了!这似乎有效。我输入一个位置,然后将该纬度/经度与剩余的 1300 个字段进行比较,以显示表格中的数据。如果有人对压缩代码有任何建议,那就太棒了!
private void btnSubmit_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != 0)
{
lblMsg.Text = "Please select Location no From DropDown for Radius search";
return;
}
else
{
if (txtRadius.Text == "")
{
lblMsg.Text = "Please enter radius value";
return;
}
double radius = Convert.ToDouble(txtRadius.Text);
searchData = txtLocNo.Text;
str = "Select latitude,longitude from details where locno='" + searchData + "'";
con.Open();
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
if (!dr.HasRows)
{
lblMsg.Text = "No Records Found";
dataGridView1.Visible = false;
con.Close();
return;
}
else
{
dr.Read();
double lat1 = dr.GetDouble(0);
double lng1 = dr.GetDouble(1);
double lat2, lng2,dist;
String loc="";
lblMsg.Text = lat1 + " " + lng1;
dr.Dispose();
str = "Select locno,latitude,longitude from details";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
loc=dr.GetString(0);
lat2 = dr.GetDouble(1);
lng2 = dr.GetDouble(2);
dist=calculateDistance(lat1,lng1,lat2,lng2);
str = "Update details set distance=" + dist + " where locno='"+loc+"'";
cmd = new OleDbCommand(str, con);
cmd.ExecuteNonQuery();
}
str = "select * from details where distance<=" + radius;
con.Close();
lblResult.Text = "Radius Search Results";
fillGrid();
}
}
}
private double calculateDistance(double lat1,double lng1,double lat2,double lng2)
{
double x= 69.1 * (lat2 - lat1);
double y = 69.1 * (lng2 - lng1) * Math.Cos(lat1 / 57.3);
double dist = Math.Sqrt(x * x + y * y);
dist = Math.Round(dist, 2);
return dist;
}
private double calculateDistance1(double lat1, double lng1, double lat2, double lng2)
{
double theta = lng1 - lng2;
double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) +
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) *
Math.Cos(deg2rad(theta));
dist = Math.Acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
dist = Math.Round(dist, 2);
return dist;
}
private double deg2rad(double deg)
{
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad)
{
return (rad / Math.PI * 180.0);
}
private void txtRadius_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '0' && e.KeyChar != '1' && e.KeyChar != '2' && e.KeyChar != '3' &&
e.KeyChar != '4' && e.KeyChar != '5' && e.KeyChar != '6' && e.KeyChar != '7' &&
e.KeyChar != '8' && e.KeyChar != '9' && e.KeyChar != '.' && e.KeyChar!= Convert.ToChar(8))
{
e.Handled = true;
}