Unity获取GPS地理位置信息

unity获取地理位置

因为项目功能需要,需要获取用户当前的位置信息,百度了一下,很多资料,发现都不能满足直自己的需求。于是整合了网上的资料,才满足自己的需求,说说需求吧:需要定位到玩家具体位置,具体到街道信息。

获取经纬度

获取经纬的方式我使用自带API, 官方说明;http://docs.unity3d.com/Documentation/ScriptReference/LocationService.Start.html在这里插入图片描述
几个重要的参数;

  1. isEnabledByUser – 检测用户设置里的定位服务是否启用(首次会弹出提示,询问用户是否同意。如果不同意,定位会失败)
  2. lastData – 最近一次测量的地理位置(LocationInfo lastData; 也就是要和 LocationInfo 关联了)
  3. status – 定位服务的状态
  4. 其他属性,自行看文档,毕竟看官方文档是我们学习知识最好和最快的方式之一,

代码如下

    IEnumerator Start()
    {
        if (!Input.location.isEnabledByUser)
        {
            Input.location.Start();

            yield break;
        }
           
        // Start service before querying location
        Input.location.Start();

        // Wait until service initializes
        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
        {
            yield return new WaitForSeconds(1);
            maxWait--;
        }

        // Service didn't initialize in 20 seconds
        if (maxWait < 1)
        {
            print("Timed out");
            yield break;
        }

        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed)
        {
            print("Unable to determine device location");
            yield break;
        }
        else
        {
            // Access granted and location value could be retrieved
            print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);

            //取出位置的经纬度
            string str = Input.location.lastData.longitude + "," + Input.location.lastData.latitude;
            Debug.Log("定位信息" +  GetLocationByLngLat(str)); 
        }

        // Stop service if there is no need to query location updates continuously
        Input.location.Stop();
    }

地址解析 Geocoder

地址解析类用于在地址和经纬度之间进行转换的服务。 本功能以异步方式将检索条件发送至服务器,通过您自定义的回调函数将结果返回,也就是说我们可以通过经纬度换算出我们的位置详情,
代码如下;

  const string key = "6bda73179a87a92394489045b32a0f46";		//去高德地图开发者申请 这个key的流量不知道被哪位同学用完了,

    /// <summary>
    /// 根据经纬度获取地址
    /// </summary>
    /// <param name="LngLatStr">经度纬度组成的字符串 例如:"113.692100,34.752853"</param>
    /// <param name="timeout">超时时间默认10秒</param>
    /// <returns>失败返回"" </returns>
    public string GetLocationByLngLat(string LngLatStr, int timeout = 10000)
    {
        string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={LngLatStr}";
        return GetLocationByURL(url, timeout);
    }

    /// <summary>
    /// 根据经纬度获取地址
    /// </summary>
    /// <param name="lng">经度 例如:113.692100</param>
    /// <param name="lat">维度 例如:34.752853</param>
    /// <param name="timeout">超时时间默认10秒</param>
    /// <returns>失败返回"" </returns>
    public string GetLocationByLngLat(double lng, double lat, int timeout = 10000)
    {
        string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={lng},{lat}";
        return GetLocationByURL(url, timeout);
    }
    /// <summary>
    /// 根据URL获取地址
    /// </summary>
    /// <param name="url">Get方法的URL</param>
    /// <param name="timeout">超时时间默认10秒</param>
    /// <returns></returns>
    private string GetLocationByURL(string url, int timeout = 10000)
    {
        string strResult = "";
        try
        {
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.ContentType = "multipart/form-data";
            req.Accept = "*/*";
            //req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
            req.UserAgent = "";
            req.Timeout = timeout;
            req.Method = "GET";
            req.KeepAlive = true;
            HttpWebResponse response = req.GetResponse() as HttpWebResponse;
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                strResult = sr.ReadToEnd();
            }
            int formatted_addressIndex = strResult.IndexOf("formatted_address");
            int addressComponentIndex = strResult.IndexOf("addressComponent");
            int cutIndex = addressComponentIndex - formatted_addressIndex - 23;
            int subIndex = formatted_addressIndex + 20;
            return strResult;
        }
        catch (Exception)
        {
            strResult = "";
        }
        return strResult;
    }

结果如下;

{"status":"1","regeocode":{"addressComponent":{"city":"福州市","province":"福建省","adcode":"350121","district":"闽侯县","towncode":"350121107000","streetNumber":{"number":"6号","location":"119.213622,26.0423319","direction":"东南","distance":"114.359","street":"高新大道"},"country":"中国","township":"上街镇","businessAreas":[[]],"building":{"name":[],"type":[]},"neighborhood":{"name":[],"type":[]},"citycode":"0591"},"formatted_address":"福建省福州市闽侯县上街镇高新大道"},"info":"OK","infocode":"10000"} 
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Unity获取高德GPS信息,你可以通过以下步骤来实现: 1. 获取高德开放平台的API密钥:首先,你需要在高德开放平台上注册开发者账号并获取API密钥。API密钥将用于访问高德地图的相关服务,包括GPS定位。 2. 导入网络库:在Unity中,你可以导入适用的网络库来进行HTTP请求。例如,你可以使用UnityWebRequest类或第三方库(如BestHTTP)来发送和接收网络请求。 3. 发送HTTP请求:使用网络库,在Unity中发送HTTP请求到高德地图的定位API接口。例如,你可以发送GET请求来获取设备的GPS位置信息。 4. 解析响应数据:一旦收到来自高德地图API的响应,你需要解析响应数据以提取所需的GPS信息。这可以通过处理JSON或XML格式的响应数据来完成,具体取决于高德地图API返回数据的格式。 5. 处理和使用数据:解析后的GPS数据可以用于在Unity中进行进一步处理和使用。例如,你可以使用这些数据来显示地图、标记位置、计算路径等。 下面是一个基本示例代码,展示了如何在Unity获取高德GPS信息: ```csharp using UnityEngine; using UnityEngine.Networking; public class GPSManager : MonoBehaviour { string apiKey = "YOUR_API_KEY"; string url = "https://restapi.amap.com/v3/ip?key={0}"; void Start() { StartCoroutine(GetGPSLocation()); } IEnumerator GetGPSLocation() { string requestUrl = string.Format(url, apiKey); UnityWebRequest webRequest = UnityWebRequest.Get(requestUrl); yield return webRequest.SendWebRequest(); if (webRequest.result == UnityWebRequest.Result.Success) { string response = webRequest.downloadHandler.text; // 解析响应数据,获取GPS信息 // ... Debug.Log("GPS Location: " + response); } else { Debug.LogError("Error getting GPS location: " + webRequest.error); } } } ``` 请注意,以上代码仅提供了一个基本的示例,具体的实现方式和代码逻辑可能会根据你所使用的网络库和高德地图API有所不同。你需要根据自己的需求和技术选择进行适当的调整。 另外,要确保你的应用程序遵守高德地图API的使用条款和限制。在使用之前,建议阅读高德地图开放平台的文档以了解更多详细信息
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值