---
title: "靠谱的根据经纬度计算两点之间距离的方法"
author: "lyj86"
date: "2019-06-04T13:56:56Z"
tags: ["经纬度", "距离"]
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2019-06-04T14:04:42Z"
id: 2441598
url: "https://lyj86.iteye.com/blog/2441598"
---

网上找的中文的例子都不靠谱，还得是英文网站好用。

网址： [https://www.movable-type.co.uk/scripts/latlong.html](https://www.movable-type.co.uk/scripts/latlong.html)

 

**Haversine formula**

Using Chrome on a middling Core i5 PC, a distance calcula­tion takes around [2 – 5 micro­seconds](https://www.movable-type.co.uk/scripts/performance/latlong-spherical.html) (hence around 200,000 – 500,000 per second). Little to no benefit is obtained by factoring out common terms; probably the JIT compiler optimises them out.

 

formula：

a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2) c = 2 ⋅ atan2( √a, √(1−a) )

d = R ⋅ c

 

 

where φ *is latitude,* λ *is longitude,* R *is earth’s radius (mean radius = 6,371km);*  
*note that angles need to be in radians to pass to trig functions!*

 

 

Javascript:

```
var R =6371e3;// metresvarφ1= lat1.toRadians();

varφ2= lat2.toRadians();varΔφ=(lat2-lat1).toRadians();

varΔλ=(lon2-lon1).toRadians();

var a =Math.sin(Δφ/2)*Math.sin(Δφ/2)+Math.cos(φ1)*Math.cos(φ2)*Math.sin(Δλ/2)*Math.sin(Δλ/2);

var c =2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));var d = R * c;
 
```

 

 

 

**Spherical Law of Cosines**

the simple [spherical law of cosines](http://mathworld.wolfram.com/SphericalTrigonometry.html)formula (cos *c* = cos *a* cos *b* + sin *a* sin *b* cos *C*) gives well-condi­tioned results down to distances as small as a few metres on the earth’s surface

 

formula: 

d = acos( sin φ1 ⋅ sin φ2 + cos φ1 ⋅ cos φ2 ⋅ cos Δλ ) ⋅ R

 

Javascript:

 

```
varφ1= lat1.toRadians(),φ2= lat2.toRadians(),Δλ=(lon2-lon1).toRadians(), R =6371e3;// gives d in metres
var d =Math.acos(Math.sin(φ1)*Math.sin(φ2)+Math.cos(φ1)*Math.cos(φ2)*Math.cos(Δλ))* R;
 
```

 

 

**Equirectangular approximation**

If performance is an issue and accuracy less important, for small distances [Pythagoras’ theorem](http://en.wikipedia.org/wiki/Pythagorean_theorem) can be used on an [equi­rectangular projec­tion](http://en.wikipedia.org/wiki/Equirectangular_projection):*

 

 

Formula

x = Δλ ⋅ cos φm   y = Δφ   d = R ⋅ √x² + y² JavaScript:

```

```

```
var x =(λ2-λ1)*Math.cos((φ1+φ2)/2);
var y =(φ2-φ1);
var d =Math.sqrt(x*x + y*y)* R;
 
```

```
 
```

 λ2就是lon2

 λ1就是lon1

 

角度和弧度换算的原理：

网址： [https://tianyelina.iteye.com/blog/756031](https://tianyelina.iteye.com/blog/756031)

Javascript实现（根据原理自己实现也很容易）： 

网址： [https://www.w3resource.com/javascript-exercises/javascript-math-exercise-33.php](https://www.w3resource.com/javascript-exercises/javascript-math-exercise-33.php)