CoordinateConverter.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class CoordinateConverter
  5. {
  6. // 计算两个经纬度之间的距离,返回值为公里
  7. public static double Haversine(double lat1, double lon1, double lat2, double lon2)
  8. {
  9. // 将纬度和经度从度转换为弧度
  10. double R = 6371.0; // 地球半径,单位为公里
  11. double dLat = ToRadians(lat2 - lat1);
  12. double dLon = ToRadians(lon2 - lon1);
  13. lat1 = ToRadians(lat1);
  14. lat2 = ToRadians(lat2);
  15. // Haversine 公式
  16. double a = Mathf.Sin((float)dLat / 2) * Mathf.Sin((float)dLat / 2) +
  17. Mathf.Cos((float)lat1) * Mathf.Cos((float)lat2) *
  18. Mathf.Sin((float)dLon / 2) * Mathf.Sin((float)dLon / 2);
  19. double c = 2 * Mathf.Atan2(Mathf.Sqrt((float)a), Mathf.Sqrt((float)(1 - a)));
  20. // 计算距离
  21. double distance = R * c;
  22. return distance;
  23. }
  24. // 将角度转换为弧度
  25. private static double ToRadians(double angle)
  26. {
  27. return angle * Mathf.Deg2Rad;
  28. }
  29. // 将经纬度转换为Unity坐标
  30. public static Vector3 GeoToUnity(double longitude, double latitude)
  31. {
  32. float x = (float)(96151.617 * longitude - 10938527.4823);
  33. float z = (float)(111468.3949 * latitude - 3339986.2697);
  34. return new Vector3(x, 0, z);
  35. }
  36. // 将Unity坐标转换为经纬度
  37. public static (double Longitude, double Latitude) UnityToGeo(Vector3 unityCoord)
  38. {
  39. double longitude = (unityCoord.x + 10938527.4823)/ 96151.617;
  40. double latitude = (unityCoord.z + 3339986.2697)/ 111468.3949;
  41. // 这里我们忽略了截距,因为我们假设Unity坐标的原点对应于经纬度的截距
  42. // 如果需要考虑截距,可以在这里添加相应的计算
  43. return (longitude, latitude);
  44. }
  45. public static Vector3 GeoToUGUI(double longitude, double latitude)
  46. {
  47. float x = (float)(355.53f * longitude - 40339.8622f);
  48. float y = (float)(409.37f * latitude - 12420.05f);
  49. return new Vector3(x, y, 0);
  50. }
  51. public static Vector3 GeoToUGUISmall(double longitude,double latitude)
  52. {
  53. float x = (float)(75.642f * longitude - 8607.658f);
  54. float y = (float)(87.990f * latitude - 2640.548f);
  55. return new Vector3(x, y, -0.400f);
  56. }
  57. public static (double Latitude, double Longitude) UGUISmallToGeo(Vector3 uiCoord)
  58. {
  59. double latitude = (uiCoord.x + 8607.658) / 75.642;
  60. double longitude = (uiCoord.y + 2640.548) / 87.990;
  61. // 这里我们忽略了截距,因为我们假设Unity坐标的原点对应于经纬度的截距
  62. // 如果需要考虑截距,可以在这里添加相应的计算
  63. return (latitude, longitude);
  64. }
  65. public static (double latitude, double longitude) UGUIToGeo(Vector3 ugui)
  66. {
  67. float x = ugui.x;
  68. float y = ugui.y;
  69. double latitude = (x + 40339.8622f) / 355.53f;
  70. double longitude = (y + 12420.05f) / 409.37f;
  71. return (latitude, longitude);
  72. }
  73. }