两种方法:
1.
getDistance: function (lat1, lng1, lat2, lng2) { lat1 = lat1 || 0; lng1 = lng1 || 0; lat2 = lat2 || 0; lng2 = lng2 || 0; var rad1 = lat1 * Math.PI / 180.0; var rad2 = lat2 * Math.PI / 180.0; var a = rad1 - rad2; var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0; var r = 6378137; return r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2))) }
2.
private const double EARTH_RADIUS = 6378.137*1000;//地球半径,单位为米 private static double rad(double d) { return d * Math.PI / 180.0; } /// <summary> /// 返回两点之间的距离,单位为米 /// </summary> /// <param name="lat1"></param> /// <param name="lng1"></param> /// <param name="lat2"></param> /// <param name="lng2"></param> /// <returns></returns> public static double GetDistance(double lat1, double lng1, double lat2, double lng2) { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double 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; return s; }
另外,附上百度地图API的算法用例:
// 百度地图API功能 var map = new BMap.Map("allmap"); map.centerAndZoom("重庆",12); //初始化地图,设置城市和地图级别。 var pointA = new BMap.Point(106.486654,29.490295); // 创建点坐标A--大渡口区 var pointB = new BMap.Point(106.581515,29.615467); // 创建点坐标B--江北区 alert('从大渡口区到江北区的距离是:'+(map.getDistance(pointA,pointB)).toFixed(2)+' 米。'); //获取两点距离,保留小数点后两位 var polyline = new BMap.Polyline([pointA,pointB], {strokeColor:"blue", strokeWeight:6, strokeOpacity:0.5}); //定义折线 map.addOverlay(polyline); //添加折线到地图上