使用JavaScript可以通过以下步骤计算两点之间的距离和方位角:
可以使用Geolocation API获取用户的地理位置信息,或者手动输入两点的经纬度。
JavaScript中的三角函数使用弧度作为单位,因此需要将经纬度转换为弧度。
const lat1Rad = lat1 * Math.PI/180;
const lon1Rad = lon1 * Math.PI/180;
const lat2Rad = lat2 * Math.PI/180;
const lon2Rad = lon2 * Math.PI/180;
可以使用Haversine公式计算两点之间的距离。
const R = 6371e3; // 地球半径,单位为米
const dLat = lat2Rad - lat1Rad;
const dLon = lon2Rad - lon1Rad;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const distance = R * c;
可以使用反三角函数计算方位角。需要注意的是,JavaScript中的反三角函数返回的是弧度值。
const y = Math.sin(lon2Rad-lon1Rad) * Math.cos(lat2Rad);
const x = Math.cos(lat1Rad)*Math.sin(lat2Rad) -
Math.sin(lat1Rad)*Math.cos(lat2Rad)*Math.cos(lon2Rad-lon1Rad);
const brng = Math.atan2(y, x);
const bearing = (brng * 180/Math.PI + 360) % 360;
最后,可以将距离和方位角输出到页面上。
console.log(`距离: ${distance.toFixed(2)}米`);
console.log(`方位角: ${bearing.toFixed(2)}度`);