How does JavaScript calculate the distance between two places? I believe there are many ways to achieve this, the next article will introduce you to JavaScript through latitude and longitude to calculate the distance between the two places.
Recently work needs, online search under the latitude and longitude to calculate the distance between the two methods, found that either the geometric method, draw, make a bunch of auxiliary lines, and then prove reasoning, or apart directly set formula. This article introduces an easy-to-understand way to find this distance.
Ideas
The earth is an irregular ellipsoid, for simplicity we calculate as a sphere.
The shortest distance between the two sides of a sphere is the length of the counterclockwise of a great circle.
Ideas are as follows:
Arc length ← Chord length (two point distance) ← Two point coordinate (Cartesian coordinates) ← Latitude and longitude
Calculation
1. Coordinate conversion
Set
The radius of the earth is $R $
The center of gravity to E 0°n 0° is connected to the x-axis
The center of gravity to E 90°n 0° is connected to the Y axis.
Center of gravity to E 0°n 90° to Z-axis
The surface of the earth is a little $A $, longitude $e $, latitude is $n $, Unit is radians
The coordinates of the $A $ are expressed as:
$ $x = r \cdot cos (n) \cdot cos (e) \\y = r \cdot cos (n) \cdot sin (e) \\z = R \cdot sin (n) $$
Code
Const R = 6371const {cos, sin, PI} = Mathlet GetPoint = (e, n) + = { //first convert angle to radians e *= pi/180 n *= pi/180
reutrn { x:r*cos (n) *cos (e), Y:r*cos (n) *sin (e), z:r*sin (n) }}
2. Calculate two-point distance according to coordinates
This is too simple to skip
3. Arc length based on chord length
This can draw a diagram to help understand:
Now known chord length $c $, radius $R $, required arc $r $ length
This is simple, just to find out the size of the $∠\alpha$:
$$\alpha = \arcsin (c/2/r) \\r = 2\alpha \cdot r$$
Code
const {ASIN} = mathconst R = 6371R = ASIN (C/2/R) *2*r
Final code
/** * Gets the distance between the two latitude and longitude * @param {Number} e1 point 1 east longitude, unit: angle, if it is West, negative * @param {number} n1 point 1 Latitude, Unit: angle, if South latitude is negative * @param {number} e2 * @param {number} n2 */function getdistance (E1, N1, E2, N2) {Const R = 6371 const {sin, cos, ASIN, PI, hypot} = Math/** Get the coordinates of points based on latitude and longitude */Let GetPoint = (e, n) + = {e *= pi/180 n *= pi/180//Here r* is removed, equivalent to the unit circle on the distance of two points, and finally will then enlarge the distance R times return {x:cos (n) *cos (e), Y:cos (n) *sin (e), Z:sin (N)}} Let A = GetPoint (e1, n1) Let B = GetPoint (e2, n2) Let C = Hypot (a.x-b.x, A.Y-B.Y, A.z-b . z) Let R = Asin (C/2) *2*r return R}