首页 > 其他分享 >unity 用gps获取经纬度,然后将经纬度通过逆地理编码转换成中文地址(百度API)

unity 用gps获取经纬度,然后将经纬度通过逆地理编码转换成中文地址(百度API)

时间:2024-07-11 11:10:13浏览次数:9  
标签:GetGps 经纬度 lastData Debug unity API location latitude Input

1.通过GPS获取经纬度

直接上代码了

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GetGPS : MonoBehaviour
{
    string GetGps = "";
    //public Button updateBtn;

    Vector2 jingWei = new Vector2();
    // Start is called before the first frame update
    void Start()
    {
        #region 初始化一次位置
        StartCoroutine(StartGPS());
        GetGps = "N:" + Input.location.lastData.latitude + " E:" + Input.location.lastData.longitude;
        jingWei.x = Input.location.lastData.latitude;
        jingWei.y = Input.location.lastData.longitude;
        GetGps = GetGps + " Time:" + Input.location.lastData.timestamp;
        //Debug.Log(GetGps);
        #endregion

        //updateBtn.onClick.AddListener(updateGps);



    }

    /// <summary>
    /// 刷新位置信息
    /// </summary>
    public Vector2 updateGps()
    {


        StartCoroutine(StartGPS());
        GetGps = "N:" + Input.location.lastData.latitude + " E:" + Input.location.lastData.longitude;
        jingWei.x = Input.location.lastData.latitude;
        jingWei.y = Input.location.lastData.longitude;
        GetGps = GetGps + " Time:" + Input.location.lastData.timestamp;
        Debug.Log(GetGps);
        return jingWei;
    }
    IEnumerator StartGPS()
    {
        // Input.location 用于访问设备的位置属性(手持设备), 静态的LocationService位置  
        // LocationService.isEnabledByUser 用户设置里的定位服务是否启用  
        if (!Input.location.isEnabledByUser)
        {
            GetGps = "isEnabledByUser value is:" + Input.location.isEnabledByUser.ToString() + " Please turn on the GPS";
            yield 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)
        {
            GetGps = "Init GPS service time out";
            yield return false;
        }

        if (Input.location.status == LocationServiceStatus.Failed)
        {
            GetGps = "Unable to determine device location";
            yield return false;
        }
        else
        {
            GetGps = "N:" + Input.location.lastData.latitude + " E:" + Input.location.lastData.longitude;
            jingWei.x = Input.location.lastData.latitude;
            jingWei.y = Input.location.lastData.longitude;
            GetGps = GetGps + " Time:" + Input.location.lastData.timestamp;
            yield return new WaitForSeconds(100);
        }
    }
    /// <summary>
    /// 停止刷新位置(节省手机电量)
    /// </summary>
    void StopGPS()
    {
        Input.location.Stop();
    }
}

 

2.通过百度的逆地理编码API进行经纬度跟中文地址的转化

进入百度地图开放平台

https://lbsyun.baidu.com/apiconsole/quota#/home

 创建服务端类型的应用

 

这是逆地理编码的接口说明:

https://lbsyun.baidu.com/faq/api?title=webapi/guide/webservice-geocoding-abroad-base

这是API调用的问题文档: https://lbsyun.baidu.com/faq/search?id=260

下面上代码:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using UnityEngine;

public class AddressTool : MonoBehaviour
{
    //https://api.map.baidu.com/reverse_geocoding/v3/?ak=您的ak&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194
    //这里使用的是百度开放平台 应用类别:服务端 的AK
    string ak = "";
    float latitude;
    float longitude;
    string url;
    //string url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak="+ ak + "&output=json&coordtype=wgs84ll&location=";

    [SerializeField] GetGPS getGPS;
    void Start()
    {
        //北京
        latitude = 40f;
        longitude = 116.467f;
        GetDiDian();
        //天津
        latitude = 39.12169f;
        longitude = 117.7334f;
        GetDiDian();

        //url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&location="+ latitude+","+ longitude;
        /*url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&extensions_poi=1&location=" + latitude + "," + longitude;

        StartCoroutine(Request());*/
        GetDiDian();
    }
    void GetDiDian()
    {
        url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&extensions_poi=1&location=" + latitude + "," + longitude;

        StartCoroutine(Request());
    }
    IEnumerator Request()
    {
        WWW www = new WWW(url);
        yield return www;

        if (string.IsNullOrEmpty(www.error))
        {
            Debug.Log(www.text);
            //ResponseBody req = JsonConvert.DeserializeObject<ResponseBody>(www.text);
            //Debug.Log(req.content.address_detail.city + " X: " + req.content.point.x + " Y: " + req.content.point.x);

            string ss=www.text;
            //Object newStudent = JsonConvert.DeserializeObject<Object>(www.text);
            //Object newStudent = JsonMgr.DeSerialize<Object>(ss);
            /*JsonData newStudent = JsonConvert.DeserializeObject<JsonData>(www.text);
            Debug.Log(newStudent.status);
            Debug.Log(newStudent.result);*/
            JObject jo = (JObject)JsonConvert.DeserializeObject(ss);
            Debug.Log(jo);
            Debug.Log(jo["result"]);
            Debug.Log(jo["result"]["pois"]);
            Debug.Log(jo["result"]["pois"][0]["addr"]);
            Debug.Log(jo["result"]["pois"][0]["name"]);
            Debug.Log(jo["result"]["pois"][0]["uid"]);
        }
    }
}
public class JsonMgr
{
    public static string Serialize<T>(T t)
    {
        return JsonConvert.SerializeObject(t);
    }

    public static T DeSerialize<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
}
class JsonData
{
    public int status;
    public JsonResult result;
}
class JsonResult
{
    public JsonLocation location;//经纬度
    string formatted_address_poi;//机构化地址
}
class JsonLocation
{
    public float lng;//经度值
    public float lat;//纬度值
}

注意:

逆地理编码的时候需要用GetGPS.cs搭配使用

而且需要提前注册号百度地图开放平台的服务端类型的应用,并获取AK码

这里解析JSON时,使用了Newtonsoft,分享链接如下:

链接:https://pan.baidu.com/s/1zoXDUr03miEKgnAk__U5YQ?pwd=cdbh
提取码:cdbh

 

标签:GetGps,经纬度,lastData,Debug,unity,API,location,latitude,Input
From: https://www.cnblogs.com/lingLuoChengMi/p/18295644

相关文章

  • 超好用!3个免费的运营商API实例
    今天推荐几个免费的API,支持在线调用,即便是小白也可轻松操作!敲黑板!!注意听课,建议收藏,非常实用!一、运营商三要素传入姓名+身份证号码+手机号,校验此三项是否一致该接口对移动支付、移动银行及其他各种移动应用都非常适用,可以确认用户身份的真实性有效识别和防止欺诈活动。......
  • Unity中用于处理 UI 的射线检测和事件处理的两种脚本
    GraphicRaycaster组件GraphicRaycaster是Unity中用于UI系统的射线检测组件。它主要用于检测屏幕上的图形界面元素(如按钮、图片、文本等)的点击事件,并将这些事件传递给相应的UI元素。主要功能射线检测:用于检测屏幕空间中的射线,确定用户点击了哪个UI元素。UI交互:处理......
  • 【uni-app+Vue3】 API请求封装:让接口调用更便捷
    前言:uni-app是一款基于Vue.js框架的跨平台开发工具,可以将代码编译成H5、小程序、App等不同平台的应用。在进行uni-app开发时,网络请求是必不可少的环节。为了方便开发,我们可以封装一些网络请求方法,以便在多个页面中复用,并且可以统一处理错误信息等问题,提高开发效率和代码质量。......
  • Ollama完整教程:本地LLM管理、WebUI对话、Python/Java客户端API应用
    老牛同学在前面有关大模型应用的文章中,多次使用了Ollama来管理和部署本地大模型(包括:Qwen2、Llama3、Phi3、Gemma2等),但对Ollama这个非常方便管理本地大模型的软件的介绍却很少。目前,清华和智谱AI联合发布开源的GLM4-9B大模型也能支持Ollama进行本地部署了(本地部署GLM-4-9B清华......
  • 06-Web API
    01DOM的概念02BOM概念除了DOM对象以外都是BOM,例如上图浏览器上的一些东西03DOM的继承关系图04节点之间的导航获取一个节点之后,可以根据这个节点去获取其它节点,称之为节点之间的导航获取节点代码示例<!DOCTYPEhtml><htmllang="en"><head><metacharset="U......
  • 在unity中被攻击时无敌的设置
    publicclassInvincible:MonoBehaviour {publicSpriteRendererrender; publicColornormalColor; publicColorflashColor; publicintduration; publicboolisInvincible;publicIEnumeratorSetInvincibility(){  isInvincible=true;  for......
  • 使用Java9 Flow API进行Reactive Programming
    importjava.util.concurrent.Flow;importjava.util.concurrent.Flow.Publisher;importjava.util.concurrent.Flow.Subscriber;publicclassReactiveExample{publicstaticvoidmain(String[]args){//创建一个发布者,发布一系列的数字Publisher......
  • 智能小程序 Ray 开发门锁 API ——日志 API 接口汇总
    查询最近一条日志记录getLatestLog引入@ray-js/ray^1.5.0以上版本可使用import{getLatestLog}from'@ray-js/ray'参数LatestLogParams属性类型必填说明devIdstring是设备ID返回LatestLogResponse结构包含日志记录的各种详细信息。函数定义示例/***查询......
  • RPC api与Rest api的区别 微服务 正反向代理
    参考链接:https://blog.csdn.net/weixin_43871785/article/details/129922143  RPC:本地化REST:国际化HTTP与RPC的关系就好比国际化与地方化的关系(可以认为标准的国际拳击手和随意的自由拳击手)。要进行跨企业服务调用时,往往都是通过HTTPAPI,虽然效率不高,但是通用,没有......
  • Java-常用API
    1-JavaAPI:指的就是JDK中提供的各种功能的Java类。2-Scanner基本使用Scanner:一个简单的文本扫描程序,可以获取基本类型数据和字符串数据构造方法:Scanner(InputStreamsource):创建Scanner对象System.in:对应的是InputStream类型,可以表示键盘输入Scannersc=n......