using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoordinateConverter { // 计算两个经纬度之间的距离,返回值为公里 public static double Haversine(double lat1, double lon1, double lat2, double lon2) { // 将纬度和经度从度转换为弧度 double R = 6371.0; // 地球半径,单位为公里 double dLat = ToRadians(lat2 - lat1); double dLon = ToRadians(lon2 - lon1); lat1 = ToRadians(lat1); lat2 = ToRadians(lat2); // Haversine 公式 double a = Mathf.Sin((float)dLat / 2) * Mathf.Sin((float)dLat / 2) + Mathf.Cos((float)lat1) * Mathf.Cos((float)lat2) * Mathf.Sin((float)dLon / 2) * Mathf.Sin((float)dLon / 2); double c = 2 * Mathf.Atan2(Mathf.Sqrt((float)a), Mathf.Sqrt((float)(1 - a))); // 计算距离 double distance = R * c; return distance; } // 将角度转换为弧度 private static double ToRadians(double angle) { return angle * Mathf.Deg2Rad; } // 将经纬度转换为Unity坐标 public static Vector3 GeoToUnity(double longitude, double latitude) { float x = (float)(96151.617 * longitude - 10938527.4823); float z = (float)(111468.3949 * latitude - 3339986.2697); return new Vector3(x, 0, z); } // 将Unity坐标转换为经纬度 public static (double Longitude, double Latitude) UnityToGeo(Vector3 unityCoord) { double longitude = (unityCoord.x + 10938527.4823)/ 96151.617; double latitude = (unityCoord.z + 3339986.2697)/ 111468.3949; // 这里我们忽略了截距,因为我们假设Unity坐标的原点对应于经纬度的截距 // 如果需要考虑截距,可以在这里添加相应的计算 return (longitude, latitude); } public static Vector3 GeoToUGUI(double longitude, double latitude) { float x = (float)(355.53f * longitude - 40339.8622f); float y = (float)(409.37f * latitude - 12420.05f); return new Vector3(x, y, 0); } public static Vector3 GeoToUGUISmall(double longitude,double latitude) { float x = (float)(75.642f * longitude - 8607.658f); float y = (float)(87.990f * latitude - 2640.548f); return new Vector3(x, y, -0.400f); } public static (double Latitude, double Longitude) UGUISmallToGeo(Vector3 uiCoord) { double latitude = (uiCoord.x + 8607.658) / 75.642; double longitude = (uiCoord.y + 2640.548) / 87.990; // 这里我们忽略了截距,因为我们假设Unity坐标的原点对应于经纬度的截距 // 如果需要考虑截距,可以在这里添加相应的计算 return (latitude, longitude); } public static (double latitude, double longitude) UGUIToGeo(Vector3 ugui) { float x = ugui.x; float y = ugui.y; double latitude = (x + 40339.8622f) / 355.53f; double longitude = (y + 12420.05f) / 409.37f; return (latitude, longitude); } }