Flutter中计算两点经纬度间方位角的方法(用于Google Map图标旋转)
计算经纬度间的方位角并应用于Google Map图标旋转
一、方位角计算逻辑
方位角是从正北方向顺时针转到两点连线的角度,范围在0-360度之间。计算需基于球面三角公式,步骤如下:
- 先将所有经纬度值从角度转换为弧度
- 计算两点的经度差
- 通过核心公式算出弧度制的方位角,再转换回角度并调整到0-360度的范围
具体公式拆解:
设起点坐标为(lat1, lon1),终点为(lat2, lon2):
- 弧度转换:
lat1_rad = lat1 × π/180lon1_rad = lon1 × π/180lat2_rad = lat2 × π/180lon2_rad = lon2 × π/180 - 经度差:
delta_lon = lon2_rad - lon1_rad - 计算核心参数:
y = sin(delta_lon) × cos(lat2_rad)x = cos(lat1_rad)×sin(lat2_rad) - sin(lat1_rad)×cos(lat2_rad)×cos(delta_lon) - 转角度并修正范围:
bearing_deg = atan2(y, x) × 180/πbearing = (bearing_deg + 360) % 360
二、JavaScript实现计算函数
function calculateBearing(lat1, lon1, lat2, lon2) { const toRadians = deg => deg * Math.PI / 180; const toDegrees = rad => rad * 180 / Math.PI; const lat1Rad = toRadians(lat1); const lon1Rad = toRadians(lon1); const lat2Rad = toRadians(lat2); const lon2Rad = toRadians(lon2); const deltaLon = lon2Rad - lon1Rad; const y = Math.sin(deltaLon) * Math.cos(lat2Rad); const x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLon); let bearingRad = Math.atan2(y, x); let bearingDeg = toDegrees(bearingRad); return (bearingDeg + 360) % 360; }
三、Google Map图标旋转实现
Google Maps的Marker组件支持rotation属性,直接将计算出的方位角赋值即可实现图标朝向终点的效果:
// 示例:北京到上海的Marker旋转 const startLatLng = new google.maps.LatLng(39.9042, 116.4074); const endLatLng = new google.maps.LatLng(31.2304, 121.4737); // 计算方位角 const bearing = calculateBearing(startLatLng.lat(), startLatLng.lng(), endLatLng.lat(), endLatLng.lng()); // 创建带旋转效果的Marker const marker = new google.maps.Marker({ position: startLatLng, map: map, // 替换为你的地图实例 icon: { url: 'your-icon-path.png', // 替换成你的图标URL anchor: new google.maps.Point(16, 16) // 锚点设为图标中心,根据实际尺寸调整 }, rotation: bearing // 传入方位角实现旋转 });
注意事项
- 图标锚点必须设置正确,否则旋转时会出现位置偏移,通常设为图标的中心坐标
- 如果需要实时更新旋转角度(比如Marker位置动态变化),可监听位置事件,重新计算方位角后调用
marker.setRotation(newBearing)更新
内容的提问来源于stack exchange,提问作者Kumar
相关产品推荐
相关产品推荐

