Last active
August 29, 2015 14:26
-
-
Save kiichi/d2453fb4119183f4787b to your computer and use it in GitHub Desktop.
Distance and Area Calculation Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| using System.Device.Location; // Add Reference | |
| namespace DistanceAreaDemo | |
| { | |
| class Program { | |
| static void Main(string[] args){ | |
| // You can write own distance function too | |
| // http://www.geodatasource.com/developers/c-sharp | |
| // but this demo uses System.Device.Location API | |
| GeoCoordinate c1 = new GeoCoordinate(36.578581, -118.291994); | |
| GeoCoordinate c2 = new GeoCoordinate(36.23998, -116.83171); | |
| double distanceInKm = c1.GetDistanceTo(c2) / 1000; | |
| Console.WriteLine(distanceInKm + " km"); | |
| //around 3.1 km2 - central park | |
| double area = GetArea(new GeoCoordinate[]{ | |
| new GeoCoordinate(40.800566,-73.957986), | |
| new GeoCoordinate(40.797187,-73.949575), | |
| new GeoCoordinate(40.764951,-73.972921), | |
| new GeoCoordinate(40.768071,-73.981676), | |
| new GeoCoordinate(40.800566,-73.957986) | |
| }); | |
| Console.WriteLine(area/1000 + " km^2"); | |
| // Or maybe ues this | |
| // https://github.com/suryapratap/GeographicLib | |
| Console.ReadKey(); | |
| } | |
| public static double Rad(double deg){ | |
| return deg * Math.PI / 180.0f; | |
| } | |
| // http://gis.stackexchange.com/questions/711/how-can-i-measure-area-from-geographic-coordinates | |
| public static double GetArea(GeoCoordinate[] coords){ | |
| var area = 0.0; | |
| var len = coords.Length; | |
| if (len > 2){ | |
| for (var i = 0; i < len - 1; i++){ | |
| GeoCoordinate p1 = coords[i]; | |
| GeoCoordinate p2 = coords[i + 1]; | |
| area += Rad(p2.Longitude - p1.Longitude) * (2 + Math.Sin(Rad(p1.Latitude)) + Math.Sin(Rad(p2.Latitude))); | |
| } | |
| area = area * 6378137.0 * 6378137.0 / 2.0; | |
| } | |
| return Math.Abs(area); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment