# 找到最接近的雙打數組

public class Location : IEnumerable
{
public string label { get; set; }
public double lat { get; set; }
public double lon { get; set; }

//Implement IEnumerable
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}

}
[HandleError]
public class HomeController : Controller
{
private List myList = new List
{
new Location {
label="Atlanta Midtown",
lon=33.657674,
lat=-84.423130},
new Location {
label="Atlanta Airport",
lon=33.794151,
lat=-84.387228},
new Location {
label="Stamford, CT",
lon=41.053758,
lat=-73.530979}, ...
}

public static int Main(String[] args)
{
string inLat = "-80.987654";
double dblInLat = double.Parse(inLat);

//here's where I would like to find the closest location to the inLat
//once I figure out this, I'll implement the Longitude, and I'll be set
}


## 最佳答案

double CalculateDistance(double lat1, double lon1, double lat2, double lon2)
{
const double R = 6371;
return Math.Acos(
Math.Sin(lat1) * Math.Sin(lat2) +
Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(lon2 - lon1)) * R;
}


double DegToRad(double deg)
{
return deg * Math.PI/180.0;
}


Location GetClosestLocation(Location origin)
{
return
(from l in locations
orderby CalculateDistance(latr, lonr, olatr, olonr))
.FirstOrDefault();
}


Location GetClosestLocation(Location origin)
{
Location closest = null;
double minDistance = double.MaxValue;
foreach (Location l in locations)
{
double dist = CalculateDistance(latr, lonr, olatr, olonr));
if (dist < minDistance)
{
minDistance = dist;
closest = l;
}
}
return closest;
}