I need a function that returns a longitude value given a lat/lon coordinate, a distance in miles, and an intersecting latitude. To do that I need to use Halversine, like discussed here: https://stackoverflow.com/a/7179026/78202. I realize that there will be two longitudes that intersect a given latitude a given distance from another ordered pair, I'd just like to get the point where I have a function that correctly returns one of them and I'll decide how to break the tie then.
I casually solved Holversine for lon1, and here's what I have. This is partly a math question, partly a programming question - what is wrong with this? There's no syntax error, I'm just not getting what I expect (see below).
function toRad(Value) {
/** Converts numeric degrees to radians */
return Value * Math.PI / 180;
}
/** returns the longitude a certain number of miles from another point given a latitude. **/
function getLon(miles, lat1, lat2, lon2) {
// see http://www.movable-type.co.uk/scripts/latlong.html
//Radius of the earth in: 1.609344 miles, 6371 km | var R = (6371 / 1.609344);
var R = 3958.7558657440545; // Radius of earth in Miles
miles = (typeof miles === "undefined") ? 1.46628357399041 : miles;
lat1 = (typeof lat1 === "undefined") ? 42.34769 : lat1;
lat2 = (typeof lat2 === "undefined") ? 42.367137 : lat2;
lon2 = (typeof lon2 === "undefined") ? -71.124383 : lon2;
var dLat = toRad( lat2-lat1 );
var sinInsideN1 = Math.sin(dLat);
var sinInsideN2 = Math.sin(miles/2*R);
var n1 = Math.pow(sinInsideN1,2);
var n2 = Math.pow(sinInsideN2,2);
var d1 = Math.cos(lat1)*Math.cos(lat2);
var inArcsin = Math.sqrt((n2-n1)/d1);
var translation = inArcsin-Math.floor(inArcsin);
var ret = -(lat1+2*Math.asin(translation))
return ret; // should be 42.34769
}
I'm getting 42.242513701215, which forms a coordinate with 42.34769 that is 8.63065661614176 mi from (42.367137,-71.124383), not 1.46628357399041 mi as expected.