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";		//去高德地圖開發者申請

    /// <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"} 
發佈了37 篇原創文章 · 獲贊 11 · 訪問量 9145
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章