I am trying to write something that will determine the distance between to sets of lat/lon coordinates.
I am using the following code which I found on this site:
public static double distance (double lat1, double lon1, double lat2, double lon2) {
double lat1 = Convert.ToDouble(latitude);
double lon1 = Convert.ToDouble(longitude);
double lat2 = Convert.ToDouble(destlat);
double lon2 = Convert.ToDouble(destlon);
double theta = toRadians(lon1-lon2);
lat1 = toRadians(lat1);
lon1 = toRadians(lon1);
lat2 = toRadians(lat2);
lon2 = toRadians(lon2);
double dist = sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(theta);
dist = toDegrees(acos(dist)) * 60 * 1.1515 * 1.609344 * 1000;
return dist;
}
My problem is that I am running into the compile error "The name 'toRadians'/'cos'/'sin/'toDegrees' does not exist in the current context..." What am I doing wrong?
You're going to need to adapt this code a bit.
As SLaks, says, you will need to define your own
toRadians()
method because .NET does not have a native version.You will also need to change the calls to cos() and sin() to be: Math.Cos() and Math.Sin()
Calculating Distance between Latitude and Longitude points...
double Lat1 = Convert.ToDouble(latitude);
I know this question is really old, but in case anyone else stumbles across this, use
GeoCoordinate
fromSystem.Device
:You may want to use the following C# class:
Usage:
Source: Chris Pietschmann - Calculate Distance Between Geocodes in C# and JavaScript
This looks like C#.
First you need to define
toRadians
andtoDegrees
:Then, to use the trigonometric functions you need to use
Math.Sin
,Math.Cos
, etc.and
Comments:
What is this? Where are
latitude
,longitude
,destlat
anddestlon
defined? Further, it appears you havelat1
,lon1
lat2
andlon2
as parameters to this method so that you can not define locals here with the same name.This is bad style. If
lat1
represents a latitude in degrees it is far better to compute a radians-equivalent value oflat1
like this:Thus replace the above with:
Lastly:
This is bad style too. The first formula and the second formula can not both possibly represent the distance that you are trying to calculate. You should assign the result of the first formula to a variable with a more meaningful name. As a worst case, at least do the following:
You can write a
toRadians
function like this:You can write a
toDegrees
function like this:You should replace
sin
andcos
withMath.Sin
andMath.Cos
.