Recently, we used the formula for calculating the distance between two points on the earth's surface based on latitude and longitude, and then implemented it using Js.
There are two ways to calculate the distance between two points on the Earth's surface.
First, the Earth is a smooth sphere by default, and then the distance between any two points is calculated. This distance is called the Great Circle distance ).
The formula is as follows:
Use js to achieve:
VaR earth_radius = 6378137.0; // unit: m var Pi = math. pi; function getrad (d) {return D * PI/180.0 ;} /*** caculate the Great Circle distance * @ Param {object} LAT1 * @ Param {object} lng1 * @ Param {object} LAT2 * @ Param {object} lng2 */Function getgreatcircledistance (LAT1, lng1, LAT2, lng2) {var radlat1 = getrad (LAT1); var radlat2 = getrad (LAT2); var A = radlat1-radlat2; var B = getrad (lng1) -getrad (lng2); var S = 2 * Math. asin (math. SQRT (math. pow (math. sin (A/2), 2) + math. cos (radlat1) * Math. cos (radlat2) * Math. pow (math. sin (B/2), 2); s = S * earth_radius; S = math. round (S * 10000)/10000.0; return s ;}
This formula is correct in most cases. There is a problem only when dealing with the relative points on the sphere, and there is a correction formula, because there is no need to find it, it can be found on the Wiki.
Of course, we all know that the earth is not a real sphere, but an elliptical sphere, so we have the following formula:
/** * approx distance between two points on earth ellipsoid * @param {Object} lat1 * @param {Object} lng1 * @param {Object} lat2 * @param {Object} lng2 */ function getFlatternDistance(lat1,lng1,lat2,lng2){ var f = getRad((lat1 + lat2)/2); var g = getRad((lat1 - lat2)/2); var l = getRad((lng1 - lng2)/2); var sg = Math.sin(g); var sl = Math.sin(l); var sf = Math.sin(f); var s,c,w,r,d,h1,h2; var a = EARTH_RADIUS; var fl = 1/298.257; sg = sg*sg; sl = sl*sl; sf = sf*sf; s = sg*(1-sl) + (1-sf)*sl; c = (1-sg)*(1-sl) + sf*sl; w = Math.atan(Math.sqrt(s/c)); r = Math.sqrt(s*c)/w; d = 2*w*a; h1 = (3*r -1)/2/c; h2 = (3*r +1)/2/s; return d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg)); }