我希望能够确定NMEA GPS位置是否在边界内。目前,我正在使用geojson .net库(https://github.com/GeoJSON-Net/GeoJSON.Net)将geojson文件转换为多边形。多边形对象Airspace会在airspace.coordinates [0] .coordinates中生成经纬度列表。
//This void will look for airspace files in /airspace directory.
private static void _getAirspace()
{
string currentDirectory = Directory.GetCurrentDirectory();
string path = System.IO.Path.Combine(@currentDirectory, "Airspace");
string[] files = Directory.GetFiles(path, "*.geojson", SearchOption.AllDirectories);
foreach (string filePath in files)
{
string fileContents = System.IO.File.ReadAllText(filePath);
Polygon airspace = JsonConvert.DeserializeObject<Polygon>(fileContents);
string json = "{\"coordinates\":[ 5.673479,52.429473 ],\"type\":\"Point\"}";
Point point = JsonConvert.DeserializeObject<Point>(json);
if (IsPointInPolygon(point,airspace)){
}
else
{
}
}
}
public static bool IsPointInPolygon(Point p, Polygon polygon)
{
double minX = polygon.Coordinates[0].Coordinates[0].Longitude;
double maxX = polygon.Coordinates[0].Coordinates[0].Longitude;
double minY = polygon.Coordinates[0].Coordinates[0].Latitude;
double maxY = polygon.Coordinates[0].Coordinates[0].Latitude;
for (int i = 1; i < polygon.Coordinates.Count; i++)
{
minX = Math.Min(polygon.Coordinates[0].Coordinates[i].Longitude, minX);
maxX = Math.Max(polygon.Coordinates[0].Coordinates[i].Longitude, maxX);
minY = Math.Min(polygon.Coordinates[0].Coordinates[i].Latitude, minY);
maxY = Math.Max(polygon.Coordinates[0].Coordinates[i].Latitude, maxY);
}
bool inside = false;
for (int i = 0, j = polygon.Coordinates.Count - 1; i < polygon.Coordinates.Count; j = i++)
{
if ((polygon.Coordinates[0].Coordinates[i].Latitude > p.Coordinates.Latitude) != (polygon.Coordinates[0].Coordinates[j].Latitude > p.Coordinates.Latitude) &&
p.Coordinates.Longitude < (polygon.Coordinates[0].Coordinates[j].Longitude - polygon.Coordinates[0].Coordinates[i].Longitude) * (p.Coordinates.Latitude - polygon.Coordinates[0].Coordinates[i].Latitude) / (polygon.Coordinates[0].Coordinates[j].Latitude - polygon.Coordinates[0].Coordinates[i].Latitude) + polygon.Coordinates[0].Coordinates[j].Longitude)
{
inside = !inside;
}
}
return inside;
}
在这种情况下,IsPointInPolygon方法始终返回true,我希望当点的坐标在多边形内时该方法返回true。