Unity之获取用户地理位置

news2024/10/6 14:23:02

1.直接利用三方API获取:

1.1 利用bilibili的api 【未知稳定性】

    public void Awake() {
		StartCoroutine(GetLocationInfoNew());
	}

    /// <summary>
	/// 利用bilibili的接口通过ip直接获取城市信息
	/// </summary>
	IEnumerator GetLocationInfoNew() {

		//UnityWebRequest publicIpReq = UnityWebRequest.Get(@"https://api.live.bilibili.com/client/v1/Ip/getInfoNew");

		var publicIpReq = new UnityWebRequest("https://api.live.bilibili.com/client/v1/Ip/getInfoNew", UnityWebRequest.kHttpVerbGET);
		publicIpReq.downloadHandler = new DownloadHandlerBuffer();

		yield return publicIpReq.SendWebRequest();
		if (!string.IsNullOrEmpty(publicIpReq.error)) {
			Debug.Log($"获取城市信息失败:{publicIpReq.error}");
			yield break;
		}
		var info = publicIpReq.downloadHandler.text;
		Debug.Log(info);

		//将json解析为object
		var resData = JsonUtility.FromJson<ResponseRootData>(info);
		Debug.Log($"address:{resData.data.addr}|province:{resData.data.province}|city:{resData.data.city}");
	}
	#region 用于接收返回值json的反序列化数据
	[System.Serializable]
	public class ResponseRootData {
		public int code;
		public string message;
		public ResponseData data;
	}
	[System.Serializable]
	public class ResponseData {
		public string addr;
		public string country;
		public string province;
		public string city;
		public string isp;
		public string latitude;
		public string longitude;
	}
	#endregion

 1.2 利用baidu api 【配额超限,需要扩充配额,需要联系官方】

string url = "http://api.map.baidu.com/location/ip?ak=bretF4dm6W5gqjQAXuvP0NXW6FeesRXb&coor=bd09ll";
	void Start() {
		StartCoroutine(Request());
	}

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

		if (string.IsNullOrEmpty(www.error)) {
			//TODO:结果为:{"status":302,"message":"天配额超限,限制访问"}	,
			Debug.Log(www.text);
			ResponseBody req = JsonConvert.DeserializeObject<ResponseBody>(www.text);
			if (req.content != null) {

				Debug.Log(req.content.address_detail.city + " X: " + req.content.point.x + " Y: " + req.content.point.x);
			}
		}
		else {
			Debug.Log(www.error);
		}
	}


	public class ResponseBody {

		public string address;
		public Content content;
		public int status;

	}

	public class Content {
		public string address;
		public Address_Detail address_detail;
		public Point point;
	}
	public class Address_Detail {
		public string city;
		public int city_code;
		public string district;
		public string province;
		public string street;
		public string street_number;
		public Address_Detail(string city, int city_code, string district, string province, string street, string street_number) {
			this.city = city;
			this.city_code = city_code;
			this.district = district;
			this.province = province;
			this.street = street;
			this.street_number = street_number;
		}
	}
	public class Point {
		public string x;
		public string y;
		public Point(string x, string y) {
			this.x = x;
			this.y = y;
		}
	}


2.获取IP地址,根据IP位置映射表计算地理位置

2.1 API: "https://api.ipify.org" 和 心知天气官网“心知天气 - 高精度气象数据 - 天气数据API接口 - 行业气象解决方案”

获取公网IP

    //ipv6:http://icanhazip.com  
    //ipv4:https://api.ipify.org  (推荐用ipv4,ipv6返回的results里面的[]可能为空)
    IEnumerator GetPublicIP() {
		var ipv4Api = @"https://api.ipify.org";
		UnityWebRequest publicIpReq = UnityWebRequest.Get(ipv4Api);
		yield return publicIpReq.SendWebRequest();
		if (!string.IsNullOrEmpty(publicIpReq.error)) {
			Debug.Log($"查询公网ip报错:{publicIpReq.error}");
			yield break;
		}
		Debug.Log("公网ip:" + publicIpReq.downloadHandler.text);
	}

根据IP获取地理信息和天气信息,json反解析的数据结构自行定义

	IEnumerator GetWeatherInfos() {
		var ipv4Api = @"https://api.ipify.org";
		UnityWebRequest publicIpReq = UnityWebRequest.Get(ipv4Api);
		yield return publicIpReq.SendWebRequest();
		if (!string.IsNullOrEmpty(publicIpReq.error)) {
			Debug.Log($"查询公网ip报错:{publicIpReq.error}");
			yield break;
		}

        //"https://www.seniverse.com/"
		var privateKey = "去心知天气官网购买免费版把私钥填写在这里~";
		string cityUri = "https://api.seniverse.com/v3/location/search.json?key=" + privateKey + "&q=" + publicIpReq.downloadHandler.text;
		UnityWebRequest cityReq = UnityWebRequest.Get(cityUri);
		yield return cityReq.SendWebRequest();
		if (!string.IsNullOrEmpty(cityReq.error)) {
			Debug.Log($"根据公网ip得到城市信息报错:{publicIpReq.error}");
			yield break;
		}
		Debug.Log(cityReq.downloadHandler.text);
		//城市信息范例:
		// {
		//	"results": [{
		//		"id": "WT3Q0FW9ZJ3Q",
		//   "name": "武汉",
		//   "country": "CN",
		//   "path": "武汉,武汉,湖北,中国",
		//   "timezone": "Asia/Shanghai",
		//   "timezone_offset": "+08:00"
		//		  }]
		// }
		JSONNode cityDataNode = JSON.Parse(cityReq.downloadHandler.text);
		string cityId = cityDataNode["results"][0]["id"];

		string weatherUri = "https://api.seniverse.com/v3/weather/now.json?key=" + privateKey + "&location=" + cityId + "&language=zh-Hans&unit=c";
		UnityWebRequest weatherReq = UnityWebRequest.Get(weatherUri);
		yield return weatherReq.SendWebRequest();

		if (!string.IsNullOrEmpty(weatherReq.error)) {
			Debug.Log($"获取城市天气信息报错:{weatherReq.error}");
			yield break;
		}

		// 天气信息范例:
		// {
		//  "results": [{
		//   "location": {
		//    "id": "WT3Q0FW9ZJ3Q",
		//    "name": "武汉",
		//    "country": "CN",
		//    "path": "武汉,武汉,湖北,中国",
		//    "timezone": "Asia/Shanghai",
		//    "timezone_offset": "+08:00"
		//   },
		//   "now": {
		//    "text": "晴",
		//    "code": "0",
		//    "temperature": "35"
		//   },
		//   "last_update": "2022-08-17T11:20:04+08:00"
		//  }]
		// }
		JSONNode weatherDataNode = JSON.Parse(weatherReq.downloadHandler.text);
		cityNameText.text = weatherDataNode["results"][0]["location"]["name"];
		cityTemperatureText.text = weatherDataNode["results"][0]["now"]["temperature"] + "°";
	}

2.2 API:"http://icanhazip.com/"

	void Start() {
		GetInIp();

		StartCoroutine(GetOutIp());
	}
	/// <summary>
	/// 获取本机的内网ip地址
	/// </summary>
	public void GetInIp() {
		var ip = "";
		IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
		for (int i = 0; i < ips.Length; i++) {
			IPAddress address = ips[i];
			if (address.AddressFamily == AddressFamily.InterNetwork) {
				ip = address.ToString();//返回ipv4的地址的字符串
			}
			//else if (address.AddressFamily == AddressFamily.InterNetworkV6)
			//{
			//	return address.ToString();//返回ipv6的地址的字符串
			//}
		}
		//找不到就返回本地
		ip = "127.0.0.1";

		Debug.Log("in ip:" + ip);
	}
	/// <summary>
	/// 借助第三方库获取本机的外网ip地址
	/// ip查询库:http://icanhazip.com/
	/// pv4: http://ipv4.icanhazip.com/
	/// ipv6:  http://ipv6.icanhazip.com/
	/// </summary>
	IEnumerator GetOutIp() {
		var ipApi = @"http://icanhazip.com/";
		ipApi = "http://ipv4.icanhazip.com/";
		UnityWebRequest request = UnityWebRequest.Get(ipApi);
		yield return request.SendWebRequest();
		//if (request.isHttpError || request.isNetworkError) {
		//	Debug.LogError(request.error);

		//	yield break;
		//}

		if (request.result == UnityWebRequest.Result.ProtocolError || request.result == UnityWebRequest.Result.ConnectionError) {
			Debug.LogError(request.error);

			yield break;
		}

		var ip = request.downloadHandler.text;
		Debug.Log("out ip:" + ip);

	}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/845598.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

在 Linux 上以 All-in-One 模式安装 KubeSphere

官方文档&#xff1a;https://www.kubesphere.io/zh/docs/v3.3/quick-start/all-in-one-on-linux/ 操作系统 最低配置 Ubuntu&#xff1a; 16.04,18.04, 20.04, 22.04 2 核 CPU&#xff0c;4 GB 内存&#xff0c;40 GB 磁盘空间Debian Buste&#xff1a;Stretch 2 核 CPU&am…

Leetcode周赛 | 2023-8-5

2023-8-5 题1体会我的代码 题2体会我的代码 题1 体会 一开始是觉得这道题是贪心的&#xff0c;选出现次数最多的元素&#xff0c;但是发现&#xff0c;当有多个元素出现次数均为最多时&#xff0c;似乎很难处理&#xff0c;就放弃了。转而问ChatGPT &#xff0c;结果让自己走上…

可视化高级绘图技巧100篇-总论

前言 优秀的数据可视化作品可以用三个关键词概括&#xff1a;准确、清晰、优雅。 准确&#xff1a;精准地反馈数据的特征信息&#xff08;既不遗漏也不冗余&#xff0c;不造成读者疏漏&误读细节&#xff09; 清晰&#xff1a;获取图表特征信息的时间越短越好 优雅&…

吃瓜教程-Task05

目录 支持向量机 间隔与支持向量 SVM基本型 对偶问题 kkt条件 例子 对偶问题 例子 对偶问题原理解释 软间隔与正则化 替代损失函数 支持向量回归 例子 支持向量机 间隔与支持向量 在样本空间中&#xff0c;划分超平面可通过如下线性方程来描述: 样本空间中任意点x到…

Doris(四)-聚合模型的使用

pre 前言 这里使用聚合模型&#xff0c;可以在导入数据的时候&#xff0c;就将部分数据做预处理&#xff0c;提高查询效率。 同样&#xff0c;因为是预处理&#xff0c;因此&#xff0c;数据细节会丢失。 1, 建表语句 create table if not exists user_landing_record_new …

基于Java+SpringBoot+Vue的篮球竞赛预约平台设计与实现(源码+LW+部署文档等)

博主介绍&#xff1a; 大家好&#xff0c;我是一名在Java圈混迹十余年的程序员&#xff0c;精通Java编程语言&#xff0c;同时也熟练掌握微信小程序、Python和Android等技术&#xff0c;能够为大家提供全方位的技术支持和交流。 我擅长在JavaWeb、SSH、SSM、SpringBoot等框架…

框框大学之——教育技术学

清一色劝退的教育技术学。。。。。。 https://www.kkdaxue.com/?current1&major%E6%95%99%E8%82%B2%E6%8A%80%E6%9C%AF%E5%AD%A6&pageSize10&sortFieldcreateTime&sortOrderdescend 总结&#xff1a; 1 杂而不经 2 摆烂劝退居多 3 适合躺平 4 考公不行 5 要多…

探秘手机隐藏的望远镜功能:开启后,观察任何你想看的地方

当今的智能手机不仅仅是通信工具&#xff0c;它们蕴藏着各种隐藏的功能&#xff0c;其中之一就是让你拥有望远镜般的观察能力。是的&#xff0c;你没有听错&#xff01;今天我们将探秘手机中隐藏的望远镜功能&#xff0c;这项神奇的功能可以让你打开后&#xff0c;轻松观察任何…

L2CS-Net: 3D gaze estimation

L2CS-Net: Fine-Grained Gaze Estimation in Unconstrained Environments论文解析 摘要1. 简介2. Related Work3. METHOD3.1 Proposed loss function3.2 L2CS-Net 结构3.3 数据集3.4 评价指标 4. 实验4.1 实验结果 论文地址&#xff1a;L2CS-Net: Fine-Grained Gaze Estimation…

R语言安装包Seurat

环境Ubuntu22&#xff0c;R4.1 also installing the dependencies ‘curl’, ‘openssl’, ‘httr’, ‘plotly’ R包安装的时候报了这个错误ERROR: dependencies httr, plotly are not available for package Seurat 解决方法&#xff0c;退出R&#xff0c;在terminal中键入…

将整数,结构体,结构体数组,链表写到文件

在之前的学习中&#xff0c;忘文件中写的内容都是字符串或字符&#xff0c;本节学习如何写入其他各种类型的数据。 回看write和read函数的形式&#xff1a; ssize_t write(int fd, const void *buf, size_t count); ssize_t read(int fd, void *buf, size_t count); 其中&a…

(论文复现)DeepAnt模型复现及应用

DeepAnt论文如下&#xff0c;其主要是用于时间序列的无监督粗差探测。 其提出的模型架构如下&#xff1a; 该文提出了一个无监督的时间序列粗差探测模型&#xff0c;其主要有预测模块和探测模块组成&#xff0c;其中预测模块的网络结构如下。 预测结构是将时间序列数据组…

mfc100u.dll丢失的多种解决方法分享,最新的修复mfc100u.dll方案

mfc100u.dll丢失可以说是见怪不怪的了&#xff0c;只要经常使用电脑的人&#xff0c;一般都会碰到一两次这种dll文件缺失的情况&#xff0c;今天主要是来给大家讲解一下mfc100u.dll丢失的多种解决方法&#xff0c;让你以后遇到这情况再也不需要头大。 一.mfc100u.dll为啥会丢失…

【论文阅读】UNICORN:基于运行时来源的高级持续威胁检测器(NDSS-2020)

UNICORN: Runtime Provenance-Based Detector for Advanced Persistent Threats NDSS-2020 哈佛大学 Han X, Pasquier T, Bates A, et al. Unicorn: Runtime provenance-based detector for advanced persistent threats[J]. arXiv preprint arXiv:2001.01525, 2020. 源码&…

无人驾驶实战-第九课(预测系统)

PNC PNCPlanning and Control&#xff0c; 其中包括&#xff1a;预测、全局路径规划、计划&#xff08;决策、路径规划、速度&#xff09;及控制。 各公司无人驾驶的整体水平 预测 很多无人驾驶的工作都需要给予预测的结果。预测的需求是准确率和实时性&#xff0c;难点是较为少…

利用MMPose进行姿态估计(训练、测试全流程)

前言 MMPose是一款基于PyTorch的姿态分析开源工具箱&#xff0c;是OpenMMLab项目成员之一&#xff0c;主要特性&#xff1a; 支持多种人体姿态分析相关任务&#xff1a;2D多人姿态估计、2D手部姿态估计、动物关键点检测等等更高的精度和更快的速度&#xff1a;包括“自顶向下”…

mybtis-plus分页查询

文章目录 2.2 代码开发2.2.1 设计DTO类2.2.2 封装PageResult2.2.3 Controller层2.2.4 Service层接口2.2.5 Service层实现类2.2.6 Mapper层 3.3 代码实现3.3.1 分页插件配置3.3.2 分页查询实现 2.2 代码开发 2.2.1 设计DTO类 根据请求参数进行封装&#xff0c;在sky-pojo模块中…

macbook 安装 Git 和 安装 Homebrew

使用MacBook 时&#xff0c;需要拉取代码&#xff0c;我们需要使用到 Git&#xff0c;但 MacBook 中并没安装&#xff0c;这里我们分享一下安装过程。其他方式可查看参考文献中的方法。 一、使用终端直接安装 在新版的 MacBook 中&#xff0c;可以使用终端直接安装 Git&#…

【流量、日志分析】常见的web流量分析、windows日志分析

1.web流量分析 1.1 特点 通常会提供一个包含流量数据的 PCAP 文件&#xff0c;有时候也会需要先进行修复或重构传输文件后&#xff0c;再进行分析。 复杂的地方在于数据包里充满着大量无关的流量信息&#xff0c;因此如何分类和过滤数据是我们需要做的。 1.2 流量包修复 例…

Docker网络模型:理解容器网络通信和连接

&#x1f337;&#x1f341; 博主猫头虎 带您 Go to New World.✨&#x1f341; &#x1f984; 博客首页——猫头虎的博客&#x1f390; &#x1f433;《面试题大全专栏》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &a…