使用者需要根据实际情况,稍做修改。废话不多说,直接上代码。
var sphereDistance = function (a, b) {
var ax = null;
var ay = null;
var bx = null;
var by = null;
for (var key in a) {
if (ax == null) {
ax = a[key] * (Math.PI / 180);
} else if (ay == null) {
ay = a[key] * (Math.PI / 180);
}
}
for (var key in b) {
if (bx == null) {
bx = b[key] * (Math.PI / 180);
} else if (by == null) {
by = b[key] * (Math.PI / 180);
}
}
var sin_x1 = Math.sin(ax), cos_x1 = Math.cos(ax);
var sin_y1 = Math.sin(ay), cos_y1 = Math.cos(ay);
var sin_x2 = Math.sin(bx), cos_x2 = Math.cos(bx);
var sin_y2 = Math.sin(by), cos_y2 = Math.cos(by);
var cross_prod = cos_y1 * cos_x1 * cos_y2 * cos_x2 + cos_y1 * sin_x1 * cos_y2 * sin_x2 + sin_y1 * sin_y2;
if (cross_prod >= 1 || cross_prod <= -1) {
if (!(Math.abs(cross_prod) - 1 < 0.000001)) {
return false;
}
return cross_prod > 0 ? 0 : Math.PI;
}
return Math.acos(cross_prod);
};
8 回复
以前写的用于计算两点坐标距离的PHP代码:
// 计算两坐标点间距离,单位:千米
define('EARTH_RADIUS', 6378.137); // 地球半径
function getDistance($lat1, $lng1, $lat2, $lng2) {
$radLat1 = deg2rad($lat1);
$radLat2 = deg2rad($lat2);
$a = $radLat1 - $radLat2;
$r = deg2rad($lng1) - deg2rad($lng2);
$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($r / 2), 2)));
$s = $s * EARTH_RADIUS;
$s = round($s * 10000) / 10000;
return $s;
}
计算方法好像跟你这个不一样的呐
这个就是呀
平面的是
var distance = function (a, b) {
var ax = null;
var ay = null;
var bx = null;
var by = null;
for (var key in a) {
if (ax == null) {
ax = a[key];
} else if (ay == null) {
ay = a[key];
}
}
for (var key in b) {
if (bx == null) {
bx = b[key];
} else if (by == null) {
by = b[key];
}
}
return Math.sqrt(Math.pow(by - ay, 2) + Math.pow(bx - ax, 2));
}