Unity使用GPS定位经纬度
发表于2018-03-28
在某些游戏中,会需要定位玩家当前位置,想实现此功能,就需要用到Unity中与设备定位(GPS经纬度)相关的API,然后通过代码控制打开权限以及获取经纬度,本篇文章就是基于此给大家介绍下使用GPS定位经纬度的方法。
代码实现:
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GPS : MonoBehaviour { private string N_Latitude; //经度 private string E_Longitude; //纬度 public Button LocationButton;// 定位按钮 void Start() { LocationButton.onClick.AddListener(() =>{ // 这里需要启动一个协同程序 StartCoroutine(StartGPS()); }); } IEnumerator StartGPS() { // Input.location 用于访问设备的位置属性(手持设备), 静态的LocationService位置 // LocationService.isEnabledByUser 用户设置里的定位服务是否启用 if (!Input.location.isEnabledByUser) { // ios需在info.plist添加key:Privacy - Location When In Use Usage Description Debug.Log("用户没有开启定位权限"); yield break; } else { // LocationService.Start() 启动位置服务的更新,最后一个位置坐标会被使用 // 定位精度10米,最小移动距离10米 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("定位超时"); yield break; } if (Input.location.status == LocationServiceStatus.Failed) { Debug.Log("定位失败"); yield break; } else { N_Latitude = Input.location.lastData.latitude.ToString(); E_Longitude = Input.location.lastData.latitude.ToString(); Input.location.Stop(); yield return null; } } }