Unity之获取用户地理位置

这篇具有很好参考价值的文章主要介绍了Unity之获取用户地理位置。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

Unity之获取用户地理位置,unity,java,数据库

lua代码

			    local info = request.downloadHandler.text
				log:Info(info)
				local json_parser_ = RapidJsonParser.new()
				info = json_parser_:Decode(info)
				if IsNull(info) or IsNull(info.data) then
					return
				end
				local addr = info.data.addr
				local city = info.data.city
				local province = info.data.province
				if IsNull(addr) or IsNull(city) or IsNull(province) then
					return
				end
				log:Info("IP:" .. addr .. "|城市:" .. city .. "|省份:" .. province)

 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/"文章来源地址https://www.toymoban.com/news/detail-630955.html

	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);

	}

到了这里,关于Unity之获取用户地理位置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序没法获取用户地理位置完整解决方案

    微信小程序官方文档提示:自 2022 年 7 月 14 日后发布的小程序,若使用该接口,需要在 app.json 中进行声明,否则将无法正常使用该接口,2022年7月14日前发布的小程序不受影响 为了查找没法定位原因花了半个小时时间认真查看官方文档,最后把wx.getLocation(Object object)接口失败

    2024年02月12日
    浏览(39)
  • uni-app获取手机号-获取用户地理位置-根据位置获取经纬度跳转高德

    1.获取手机号首先要先登录拿到code,用code去获取session_key 2.获取 code需要知道自己的AppID(小程序ID)和AppSecret(小程序密钥) 3.解密后得到手机号  登录微信公众平台拿到自己的AppID(小程序ID)和AppSecret(小程序密钥)  微信公众平台  补充获取 code: 补充 获取openId: 获取session_key:

    2024年02月03日
    浏览(59)
  • 用户Ip地址和百度地图api接口获取用户地理位置(经纬度坐标,城市)

    ?php //获取用户ip(外网ip 服务器上可以获取用户外网Ip 本机ip地址只能获取127.0.0.1) function   getip(){      if (! empty ( $_SERVER [ \\\"HTTP_CLIENT_IP\\\" ])){      $cip   =  $_SERVER [ \\\"HTTP_CLIENT_IP\\\" ];      }      else   if (! empty ( $_SERVER [ \\\"HTTP_X_FORWARDED_FOR\\\" ])){      $cip   =  $_SERVER [ \\\"HTTP_X_FOR

    2024年02月11日
    浏览(56)
  • 如何获取用户请求的真实ip,并返回访问者的ip地理位置?node,vue

    方式1、前端调用免费公共接口获取 前端获取访问者的真实的外网ip,可以通过调用接口https://api.ipify.org/来获取。你也可以直接在网页上访问它来看自己的外网ip。 ipify介绍: ipify是一个免费的公共 API,用于获取设备的公共 IP 地址。它通过查询服务器获取用户的 IP 地址,并将

    2024年03月15日
    浏览(36)
  • (Java版)根据ip获取地理位置以及相关信息

    1.首先我们需要进入地图开放平台的官网,根据提示注册账号,以百度地图为例: https://lbsyun.baidu.com/ 我们新用户登录之后会弹出这个页面,选择个人爱好者进入完成注册 成功之后我们会进入到下面这个页面,如果没有申请ak的小伙伴在控制台看板这一块是有一个流程指引的

    2024年02月08日
    浏览(22)
  • 使用uniapp开发获取地理位置

    老板要求做一个微信小程序,后面又希望能转为app. 所以选择了uniapp开发. 我的体验和感想就是以后不用uniapp了. 资源不多,学习了可能用处也不大.适合外包的干.这里写一下使用uniapp开发微信小程序获取地理位置 基本逻辑是使用uniapp的api首先获得地理经纬度位置等信息(在这之前

    2024年02月07日
    浏览(39)
  • 通过ip获取地理位置信息

    GeoLite2-City.mmdb 文件是 MaxMind 公司提供的一个免费的 IP 地址与城市地理位置映射数据库文件。它包含了 IP 地址范围与对应的城市、地区、国家、经纬度等地理位置信息的映射。这种数据库文件可以用于识别访问您的应用程序或网站的用户的地理位置,从而实现针对不同地区的

    2024年02月12日
    浏览(34)
  • Java编程技巧:获取ip地址、通过ip获取地理位置、获取客户端操作系统、获取客户端浏览器、获取主机名、获取操作系统、获取系统架构

    说明: 大家直接去对应项目位置找到代码,然后看着复制就行了 1.1、若依(自己写的代码) 项目:https://gitee.com/y_project/RuoYi 子模块:ruoyi-common 所在类:com.ruoyi.common.utils.IpUtils 所在方法:getIpAddr 详细位置:整个方法 1.2、Snowy(借助hutool工具包) 项目:https://gitee.com/xiaonuo

    2024年02月04日
    浏览(49)
  • Golang — 根据IP获取地理位置信息

    1 ip2region 2 geoip2-golang ip2region 是一个离线IP地址定位库和IP定位数据管理框架,10微秒级别的查询效率,提供了众多主流编程语言的 xdb 数据生成和查询客户端实现。 特点: 是一个开源的IP地理位置库。 标准化的数据格式 每个 ip 数据段的 region 信息都固定了格式:国家|区域|省

    2024年02月14日
    浏览(33)
  • 微信小程序 通过获取地理位置查看天气

      1.在app.json中写入 2.申请和风天气APIKEY 和风天气开发平台 ~ 高效强大的天气API,天气SDK和天气插件 3.在js文件中设置变量 4.获取天气代码  5.根据坐标获取城市  6.获取天气情况   结束啦。

    2024年02月09日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包