using UnityEngine;
using System.Collections;
public class GetGPS : MonoBehaviour
{
void StopGPS()
{
Input.location.Stop();
}
public void StartGetGPS()
{
StartCoroutine(StartGPS());
}
IEnumerator StartGPS()
{
// Input.location 用于访问设备的位置属性(手持设备), 静态的LocationService位置
// LocationService.isEnabledByUser 用户设置里的定位服务是否启用
if (!Input.location.isEnabledByUser)
{
Debug.Log ("请开启GPS权限!");
}
// LocationService.Start() 启动位置服务的更新,最后一个位置坐标会被使用
Input.location.Start(10.0f, 10.0f);
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
// 暂停协同程序的执行(1秒)
yield return new WaitForSeconds(1);
maxWait--;
}
if (maxWait < 1)
{
Debug.Log("Init GPS service time out");
}
if (Input.location.status == LocationServiceStatus.Failed)
{
Debug.Log("Unable to determine device location");
}
else
{
SetPlayerPlace();
yield return new WaitForSeconds(100);
}
}
void SetPlayerPlace()
{
if (Input.location.lastData.longitude!=0)
{
Debug.Log("经度:"+Input.location.lastData.longitude+" 纬度:"+Input.location.lastData.latitude);
}
else
{
Debug.Log("获取失败!");
}
Input.location.Stop();
}
//两个经纬度 算距离
private const double EARTH_RADIUS = 6371010;
/// <summary>
/// 计算两点位置的距离,返回两点的距离,单位:米
/// 该公式为GOOGLE提供,误差小于0.2米
/// </summary>
/// <param name="lng1">第一点经度</param>
/// <param name="lat1">第一点纬度</param>
/// <param name="lng2">第二点经度</param>
/// <param name="lat2">第二点纬度</param>
/// 34.65 33.22 18.99 17.11
/// <returns></returns>
public static string GetDistance(string[] pos1, string[] pos2)
{
if (pos1 == null || pos2 == null || pos1[0] == null || pos2[0] == null)
{
return "位置未知";
}else{
double radLat1 = Rad(double.Parse(pos1[0]));
double radLng1 = Rad(double.Parse(pos1[1]));
double radLat2 = Rad(double.Parse(pos2[0]));
double radLng2 = Rad(double.Parse(pos2[1]));
double a = radLat1 - radLat2;
double b = radLng1 - radLng2;
double result = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2))) * EARTH_RADIUS;
if (result > 1000)
{
double resultG = result / 1000;
return Convert.ToDouble(resultG).ToString("0.00") + "公里";
}
else
{
return Convert.ToDouble(result).ToString("0.00") + "米";
}
}
}
/// <summary>
/// 经纬度转化成弧度
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
private static double Rad(double d)
{
return (double)d * Math.PI / 180d;
}
}