Unity3D官方给开发者提供了定位相关的API,可以在官方文档搜索Location
LocationService
1.isEnabledByUser -- 用户设置里的定位服务是否启用
2.lastData -- 最近一次测量的地理位置
3.status -- 定位服务的状态(Stopped服务停止,Initializing正在初始化,Running正在运行,Failed用户拒绝访问位置)
4.Start()方法有桑重载,主要是设置desiredAccuracyInMeters(服务所需的精度,默认值是10米)updateDistanceInMeters(最小距离,默认值是10米)这两个参数
5.Stop ( ) -- 停止定位服务的定位更新,耗电量比较大,要及时关闭
LocationInfo
1.altitude -- 海拔高度
2.horizontalAccuracy -- 水平精度
3.latitude -- 纬度
4.longitude -- 经度
5.timestamp -- 最近一次定位的时间戳,从1970开始
6.verticalAccuracy -- 垂直精度
但是官方提供的API我们只能获取经纬度信息,还需要借助第百度地图开放平台来转换为地理位置信息,在定位服务中找到获取密钥,创建服务端应用,复制密钥
贴代码,详情见注释
//负责启动或者关闭地理定位
private const string ak = "百度地图地理位置转换授权码";
public static async void GetLocationMsg()
{
if(!Input.location.isEnabledByUser) //用户位置信息未启用
{
return;
}
Input.location.Start(500,500);//启动定位服务
int maxWait = 5;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)//等待定位服务初始化
{
await ETModel.Game.Scene.GetComponent<ETModel.TimerComponent>().WaitAsync(1000);//ET框架内容,等待1000毫秒,可以改用协程等待
maxWait--;
}
if (maxWait < 1 || Input.location.status == LocationServiceStatus.Failed)//启动失败
return;
else
{
//获取经度纬度信息
string latitude = Input.location.lastData.latitude.ToString();
string longitude = Input.location.lastData.longitude.ToString();
GetAdress(latitude,longitude);
}
}
public static async void GetAdress(string Latitude,string Longitude)
{
float latitude;
float longitude;
string location = "";
if (float.TryParse(Latitude,out latitude)&& float.TryParse(Longitude,out longitude))
{
//填入百度密钥,经纬度信息
string addressUrl = string.Format("http://api.map.baidu.com/geocoder/v2/?output=json&ak={0}&location={1},{2}",ak,latitude,longitude);
//可以用UnityWebRequestAsync去获取地理位置信息,此处为ET框架内容
using (UnityWebRequestAsync webRequestAsync = ETModel.ComponentFactory.Create<UnityWebRequestAsync>())
{
await webRequestAsync.DownloadAsync(addressUrl);
location = webRequestAsync.Request.downloadHandler.text;//获取到地理位置信息,Json数据,需要转换
}
}
}