Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create circle coordinates given central lat/long and radius

Tags:

c#

I'm creating an application to create a circle of any radius given a central lat/lon coordinate. What I need to do is take the initial lat/lon coordinates and radius and calculate the points for the circle and add them to a dictionary list.

Here's what I have so far, but wit this, I get an error saying that 'An item with the same key has already been added' which leads me believe that it isn't actually converting the circle coordinates correctly.

private const double EARTH_RADIUS_NM = 3437.670013352;

private void plot(double lat, double lon, double radius)
{
    var coords = new Dictionary<double, double>();

    lat = ConvertToRadians(lat);
    lon = ConvertToRadians(lon);
    double d = radius / EARTH_RADIUS_NM;
    for(int x = 0; x <= 360; x++)
    {
        double brng = ConvertToRadians(x);
        var latRadians = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lat) * Math.Sin(d) * Math.Cos(brng));
        var lngRadians = lon + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat), Math.Cos(d) - Math.Sin(lat) * Math.Sin(latRadians));

        coords.Add(latRadians, lngRadians);
    }
}

public double ConvertToRadians(double angle)
{
    return (angle * Math.PI) / 180;
}

Example of use:

plot(33.9331486, -118.4320114, 0.5);

Can someone point me in the right direction?

like image 627
Nicholas Avatar asked Feb 26 '15 19:02

Nicholas


2 Answers

You are entering the coordinates correctly. The problem is that a Dictionary is not the correct data type to be using for your data storage. A circle will always hit the same X coordinate in the positive and negative heights over your y-axis.

You'll want to create a simple class to store the two coordinates, and make a List of them:

public class Coordinate 
{
    public double Lat { get; set; }
    public double Lon { get; set; }

    public Coordinate(double lat, double lon) 
    {
        this.Lat = lat;
        this.Lon = lon;
    }
}

Then inside your method, have var coords = new List<Coord>();. Then where you're currently assigning them now, just do the following:

coords.Add(new Coordinate(lat, lon));
like image 135
krillgar Avatar answered Nov 03 '22 18:11

krillgar


You should not use a Dictionary<,> since it will not allow two points with the same 1st coordinate.

Use instead something like List<Tuple<double, double>> or List<Point>.

like image 43
Jeppe Stig Nielsen Avatar answered Nov 03 '22 18:11

Jeppe Stig Nielsen