Notifications
Article
经纬度转换空间坐标
Published 6 months ago
224
0
将经纬度转换为空间坐标的需求
项目中有时候需要用到经纬度定位,不同地图sdk经纬度坐标标准不一样,导致获取到的经纬度数值有偏差,想要根据已有的经纬度数值,将其转换为场景内可视化的空间坐标。需要对场景进行一定的设置,使其类似经纬度的空间坐标。转换思路为,获取经纬度,计算经纬度空间比例,再在场景中根据比例还原场景空间坐标。

选取一定的地图区域,要定义一个片面,需要三个坐标。在场景中设置其空间坐标的左下角及右上角,会自动计算出左上角,即三个空间坐标。地图范围越小越精准,范围越到,则偏差越大,因为在地图上选取范围时是根据肉眼去选择位置的,一个像素的偏差就有可能导致精准度发生较大变化。
设置完基准点后,就可以根据地图获取到经纬度,转换为场景内容的三维空间坐标,如此,就可以进行需要的操作了。
using UnityEngine; #if UNITY_EDITOR using UnityEditor; [CustomEditor(typeof(J_MapLocationXYHelper_20170428))] public class J_MapLocationXYHelper_20170428_Editor : Editor { public override void OnInspectorGUI() { EditorGUILayout.HelpBox("Y轴与地图角度朝向一致", MessageType.Info); base.OnInspectorGUI(); } } #endif public class J_MapLocationXYHelper_20170428 : MonoBehaviour { public static J_MapLocationXYHelper_20170428 Inst; public _coners m_coners = new _coners(); [System.Serializable] public struct _coners { public GameObject _leftBottom; public _dVector2 _vleftBottom; [Space(10)] public GameObject _rightTop; public _dVector2 _vrightTop; } [System.Serializable] public struct _dVector2 { public double x; public double y; } #if UNITY_EDITOR void OnDrawGizmos() { var tPos = m_coners._leftBottom.transform.localPosition; tPos.y = 0; m_coners._leftBottom.transform.localPosition = tPos; var tPos1 = m_coners._rightTop.transform.localPosition; tPos1.y = 0; m_coners._rightTop.transform.localPosition = tPos1; Vector3 _LB_Pos = m_coners._leftBottom.transform.position; Vector3 _RT_Pos = m_coners._rightTop.transform.position; Vector3 _temp_LB_to_RT = _RT_Pos - _LB_Pos; Vector3 _LT_Pos = _LB_Pos + Vector3.Project(_temp_LB_to_RT, transform.forward); Vector3 _RB_Pos = _LB_Pos + Vector3.Project(_temp_LB_to_RT, transform.right); Gizmos.color = Color.red; Gizmos.DrawLine(_LB_Pos, _LT_Pos); Gizmos.DrawLine(_LT_Pos, _RT_Pos); Gizmos.DrawLine(_RT_Pos, _RB_Pos); Gizmos.DrawLine(_RB_Pos, _LB_Pos); } #endif void Awake() { Inst = this; } void Start() { //GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube); //obj.transform.position = J_GetWorldPos(118.188068, 24.497364); } /// <summary> /// 将经纬度换算成场景内的位置 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public Vector3 J_GetWorldPos(double x, double y) { Vector3 _LB_Pos = m_coners._leftBottom.transform.position; Vector3 _RT_Pos = m_coners._rightTop.transform.position; Vector3 _temp_LB_to_RT = _RT_Pos - _LB_Pos; double _worldWidth = m_coners._vrightTop.x - m_coners._vleftBottom.x;//世界经纬度 宽 double _worldHeight = m_coners._vrightTop.y - m_coners._vleftBottom.y;//高 Vector3 _vWidth = Vector3.Project(_temp_LB_to_RT, transform.right);//场景内模型 宽向量 Vector3 _vHeight = Vector3.Project(_temp_LB_to_RT, transform.forward);//高向量 float xRateS = (float)((x - m_coners._vleftBottom.x) / _worldWidth); float yRateS = (float)((y - m_coners._vleftBottom.y) / _worldHeight); var _resultPos = _LB_Pos + xRateS * _vWidth + yRateS * _vHeight; return _resultPos; } }

Jason_Ni
软件开发工程师 - Programmer
6
Comments