- Build-in
- Mapbox
- Go Map
基于位置服务 (Location Based Services,LBS)是指围绕地理位置数据而展开的服务,其由移动终端使用无线通信网络 (或卫星定位系统),基于空间数据库,获取用户的地理位置坐标信息并与其他信息集成以向用户提供所需的与位置相关的增值服务。
在Unity的官方文档中,与设备定位(GPS经纬度、水平精度等等)相关的API有两个:LocationService 和 LocationInfo 。 其中, LocationService 负责启动和关闭定位服务。 LocationInfo 在服务启动后,获取定位数据信息。
- LocationService
- LocationInfo
- 测试工程
1. LocationService
1.1 描述
位置功能接口
1.2 属性
isEnabledByUser | 用户设置里的定位服务是否启用 |
lastData | 最近一次测量的地理位置(LocationInfo lastData; 也就是要和 LocationInfo 关联了) |
status | 定位的服务状态 |
定位的服务状态包括:
- Stopped:Location service is stopped. 定位服务已经停止
- Initializing:Location service is initializing, some time later it will switch to. 定位服务正在初始化,在一段时间后,状态会切换回来。
- Running:Location service is running and locations could be queried. 位置服务正在运行,位置可以获取。
- Failed:Location service failed (user denied access to location service). 位置服务失败(用户拒绝访问位置服务)。
1.3 方法
2. LocationInfo
2.1 描述
描述设备位置,单位为“米”。
2.2 属性
altitude | 海拔高度 |
horizontalAccuracy | 水平精度 |
latitude | 纬度 |
longitude | 经度 |
timestamp | 最近一次定位的时间戳,从1970开始 |
verticalAccuracy | 垂直精度 |
3. 测试工程
- 新建一个GetGPS的脚本
- 场景中新建一个Button,用来刷新位置
- 场景中新建一个Text用来展示位置数据
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 = 28;
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";
return false;
}
// 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) {
this.gps_info = "Init GPS service time out";
return false;
}
if (Input.location.status == LocationServiceStatus.Failed) {
this.gps_info = "Unable to determine device location";
return false;
}
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);
}
}
}