I am trying to find the straight distance from a point C to the beach. Beach line is defined by points A and B and with the Haversine formula I get the distance from C (my marker in Google Maps) to a point D in the AB beach line perpendicular to C.
Everything works fine but the point D is not the right one. I use this code to find D:
function get_perp(C){
var A = { lat:33.345678, lng:-117.518921 };
var B = { lat:33.100678, lng:-117.318492 };
t = ((C.lat-A.lat)*(B.lat-A.lat)+(C.lng-A.lng)*(B.lng-A.lng))/((B.lat-A.lat)*(B.lat-A.lat)+(B.lng-A.lng)*(B.lng-A.lng));
var D = { lat:0,lng:0};
D.lat = A.lat + t*(B.lat-A.lat);
D.lng = A.lng + t*(B.lng-A.lng);
return D;
}
Returned D point is indeed a point on the line but it is not perpendicular to C. It is when the AB line is horizontal or vertical, but when it is not the angle between AB and CD is not right.
I've tried another functions I've found here but all of them cause the same result.
In this fiddle it is the whole process and if you zoom enough you can see the AB and CD lines are not perpendicular: Shortest distance from AB to C
EDIT: playing with it in geogebra I can see the function is OK in finding the point. The error happens then when google maps api represents the point. Geogebra