获取两点之间的距离,两个经纬度直接的距离
手机上网时,经常遇到当前某个地点离我现在的距离有多少米,在做项目时,有的是从接口中返回的值,有的只能自己写了,哈哈!!!
例如:
代码如下:
function newCommon(){
//这段代码是网上搜的,但是忘记了那个网站
this.getDistanceOfJW = function(location1,location2){
function Rad(d){
return d * Math.PI / 180.0;
}
function GetDistance(lat1,lng1,lat2,lng2){
var radLat1 = Rad(lat1);
var radLat2 = Number(Rad(lat2));
var a = Number(radLat1 - radLat2);
var b = Rad(lng1) - Rad(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 *6378.137 ;
s = Math.round(s * 10000) / 10;
return s;
}
return GetDistance(location1["lat"],location1["lng"],location2["lat"],location2["lng"]) ;
}
this.getnums = function(num){
var intNum = num*10;
intNum = parseInt(intNum);
return intNum/10;
}
}
var commoms=new newCommon();
//经纬度 需要一致 例如百度的 如果两者之间经纬度不同,需要转换
var option1 = {"lat":116.357889,"lng":39.961256};
var option2 = {"lat":116.432054,"lng":39.937803};
var getM=commoms.getDistanceOfJW(option1,option2),
getMS;
//判断 如果获取的数小于1000米就使用米,则使用千米
if(getM < 1000){
getMS=getM+'m';
}else{
getMS=commoms.getnums(getM/1000)+'km';
}
console.log(getMS);
注:
经纬度需要一致,不同之间的经纬度需要转换