Haversine formula Unity
So I'm trying to use the haversine formula in Unity to get the distance between two different points (latitude and longitud given). The code is working (no errors) but I keep gettting a worng result. I followed the entire formula so I don't really know where the math/code problem is. Any idea?
Here's the code:
public float lat1 = 42.239616f;
public float lat2 = -8.72304f;
public float lon1 = 42.239659f;
public float lon2 = -8.722305f;
void operacion(){
float R = 6371000; // metres
float omega1 = ((lat1/180)*Mathf.PI);
float omega2 = ((lat2/180)*Mathf.PI);
float variacionomega1 = (((lat2 - lat1)/180)*Mathf.PI);
float variacionomega2 = (((lon2 - lon1) / 180) * Mathf.PI);
float a = Mathf.Sin(variacionomega1/2) * Mathf.Sin(variacionomega1/2) +
Mathf.Cos(omega1) * Mathf.Cos(omega2) *
Mathf.Sin(variacionomega2/2) * Mathf.Sin(variacionomega2/2);
float c = 2 * Mathf.Atan2(Mathf.Sqrt(a), Mathf.Sqrt(1-a));
float d = R * c;
}
There's nothing special in the way Unity handles math. Sin, Cos, PI are all the same are usual. Even Atan2 is a standard "computer math" function. You'd probably have better luck showing this to someone in a non-Unity forum who understands, ummm, Pirates(?) or whoever uses longitude.
Answer by daniciech · Apr 14, 2020 at 12:09 PM
Lo he resulto asi, en tus coordenadas de origen esta duplicado el la conversion:
float omega1 = ((lat1/180)*Mathf.PI); float omega2 = ((lat2/180)*Mathf.PI);
pienso esa parte es innesesaria.
Me base en la formula Haversine de esta pagina: http://www.movable-type.co.uk/scripts/gis-faq-5.1.html
float R = 6378000; // metres float variacionomega1 = (((lat2 - lat1) / 180) Mathf.PI); float variacionomega2 = (((lon2 - lon1) / 180) Mathf.PI);
float a = (Mathf.Sin(variacionomega1 / 2) * Mathf.Sin(variacionomega1 / 2)) +
(Mathf.Cos(lat1) * Mathf.Cos(lat2) *
Mathf.Sin(variacionomega2 / 2) * Mathf.Sin(variacionomega2 / 2));
float c = 2 * Mathf.Atan2(Mathf.Sqrt(a), Mathf.Sqrt(1 - a));
float d = R * c;