今天项目 遇到一个求 设备间距离的需求。考虑经纬度来实现,拷贝别人代码,加上距离函数做了个demo,主要是获得经纬度。亲测 出包Ios 与android 皆可用(Android 注意要将设置里面的位置 打开),即可实现获得当前经纬度,至于距离方面地理数学知识就可以解决了,下面也实现了,不过没测距离是否准确,先完成任务先。
using UnityEngine;
using System.Collections;public class GetGPS : MonoBehaviour {
public string gps_info = "";
public int flash_num = 1;
// Use this for initialization
void Start () {
}
void OnGUI () {
GUI.skin.label.fontSize = 22;
GUI.Label(new Rect(20,20,600,48),this.gps_info);
GUI.Label(new Rect(20,50,600,48),this.flash_num.ToString());
GUI.skin.button.fontSize = 50;
if (GUI.Button(new Rect(Screen.width/2-110,200,220,85),"GPS定位"))
{
// 这里需要启动一个协同程序
StartCoroutine(StartGPS());
}
if (GUI.Button(new Rect(Screen.width/2-110,500,220,85),"刷新GPS"))
{
this.gps_info = "N:" + Input.location.lastData.latitude + " E:"+Input.location.lastData.longitude;
this.gps_info = this.gps_info + " Time:" + Input.location.lastData.timestamp;
this.flash_num += 1;
}
}
// Input.location = LocationService
// LocationService.lastData = LocationInfo
void StopGPS () {
Input.location.Stop();
}
IEnumerator StartGPS () {
// Input.location 用于访问设备的位置属性(手持设备), 静态的LocationService位置
// LocationService.isEnabledByUser 用户设置里的定位服务是否启用
if (!Input.location.isEnabledByUser) {
this.gps_info = "isEnabledByUser value is:"+Input.location.isEnabledByUser.ToString()+" Please turn on the GPS";
}else{
// LocationService.Start() 启动位置服务的更新,最后一个位置坐标会被使用
Input.location.Start(300.0f, 300.0f);
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
// 暂停协同程序的执行(1秒)
yield return new WaitForSeconds(1);
maxWait--;
}
if (maxWait < 1) {
this.gps_info = "Init GPS service time out";
}else if (Input.location.status == LocationServiceStatus.Failed) {
this.gps_info = "Unable to determine device location";
}else{
this.gps_info = "N:" + Input.location.lastData.latitude + " E:"+Input.location.lastData.longitude;
this.gps_info = this.gps_info + " Time:" + Input.location.lastData.timestamp;
yield return new WaitForSeconds(100);
}
}
}
//参数为两个经纬度的数值 获得之间的间距
public static float getDistance(float lat1,float lng1,float lat2,float lng2)
{float a, b, R;
R = 6378137; //地球半径
lat1 = lat1 * Mathf.PI / 180.0f;
lat2 = lat2 * Mathf.PI / 180.0f;
a = (lat1 - lat2);
b = (lng1 - lng2) * Mathf.PI / 180.0f;
float d;
float sa2, sb2;
sa2 = Mathf.Sin(a / 2.0f);
sb2 = Mathf.Sin(b / 2.0f);
d = 2 * R * Mathf.Asin(Mathf.Sqrt(sa2 * sa2 + Mathf.Cos(lat1) * Mathf.Cos(lat2) * sb2 * sb2));
return d;
}
private static float rad(float d)
{
return d * Mathf.PI / 180.0f;
}
}