4

I know how to use the javascript to calculate the radius by using the below code

var center = new google.maps.LatLng(3.2987599, 102.6872022);
var latLng = new google.maps.LatLng(3.0987599, 101.6872022);
var distanceInMetres = google.maps.geometry.spherical.computeDistanceBetween(center, latLng);

But how to convert the google.maps.geometry.spherical.computeDistanceBetween into C# function?

Louisth
  • 686
  • 2
  • 7
  • 18

3 Answers3

5

Distance between 2 points: (lat1,lon1) to (lat2,lon2)

distance = acos(
     cos(lat1 * (PI()/180)) *
     cos(lon1 * (PI()/180)) *
     cos(lat2 * (PI()/180)) *
     cos(lon2 * (PI()/180))
     +
     cos(lat1 * (PI()/180)) *
     sin(lon1 * (PI()/180)) *
     cos(lat2 * (PI()/180)) *
     sin(lon2 * (PI()/180))
     +
     sin(lat1 * (PI()/180)) *
     sin(lat2 * (PI()/180))
    ) * 3959

3959 is the Earth radius in Miles. Replace this value with radius in KM, (or any other unit), to get results on the same unit.

You can verify your implementation by comparing to this worked example:

Marcelo
  • 9,387
  • 3
  • 35
  • 40
  • The formula is work, to convert js to C# as this google.maps.geometry.spherical.computeDistanceBetween the 3959 i use 6371 the earth distance instance using earth radius. – Louisth Oct 31 '12 at 10:55
2

i have write the C# solution to calculate the distance to convert

var distanceInMetres = google.maps.geometry.spherical.computeDistanceBetween(center, latLng);

into C#. Below is the code i have using. 6371 is the radius of the Earth.

    //Calculate distance earth between 2 coordinate point
    double e = lat * (Math.PI / 180);
    double f = lng * (Math.PI / 180);
    double g = lat2 * (Math.PI / 180);
    double h = lng2 * (Math.PI / 180);
    double i =
        (Math.Cos(e) * Math.Cos(g) * Math.Cos(f) * Math.Cos(h)
        + Math.Cos(e) * Math.Sin(f) * Math.Cos(g) * Math.Sin(h)
        + Math.Sin(e) * Math.Sin(g));
    double j = Math.Acos(i);
    double k = (6371 * j);  //Distance in KM
Louisth
  • 686
  • 2
  • 7
  • 18
  • I found out that if you use this as a service on a site, it is better to make a simple check before starting everyhting (saves a lot of computation time) if ((lat == lat2) && (lng == lng2)) return 0; – Sergiu Mindras Aug 27 '15 at 12:37
0

The distance between 2 lat/long points can be calculated with the haversine formula, which is described here http://en.wikipedia.org/wiki/Haversine_formula

There also is another question here at stackoverflow about more or less the same issue: Calculate distance between two latitude-longitude points? (Haversine formula)

Community
  • 1
  • 1