unity版本:2019.1.0f2
1.需要高德地图的key,去官网搞一个就行->高德的静态地图教程
2.然后将脚本挂在一个plane(Map_Tile)上就行了
3.加一个button,并将Onclick设置为下面的样子就完事了,然后导出,在手机上运行。
ps:精度不是很准,经纬度信息正常需要精确到小数点后十位,但这个返回最多五位好像是,,希望有大佬能告诉我怎么改
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class MapTile : MonoBehaviour
{
public string gps_info = "";
public string otherinfo = "";
public int flash_num = 1;
private string url;
void Awake()
{
StartCoroutine(StartGPS());
}
void Start()
{
}
void Update()
{
url = "https://restapi.amap.com/v3/staticmap?" + "location=" + this.gps_info + "&zoom=17&size=400*400&key=bdc879e247d66224ddbccdca57df298f";
//将这里面的key换成你自己的key
}
public void OnClickRefreshBtn()
{
this.gps_info = Input.location.lastData.longitude + "," + Input.location.lastData.latitude;
this.otherinfo = " Time:" + Input.location.lastData.timestamp;
this.flash_num += 1;
Download(url);
Debug.Log(url);
}
void OnGUI()
{
GUI.Label(new Rect(20, 10, 600, 48), this.gps_info);
GUI.Label(new Rect(20, 100, 600, 48), this.otherinfo);
GUI.Label(new Rect(20, 50, 600, 48), this.flash_num.ToString());
}
void Download(string url)
{
StartCoroutine(MapDownload(url));
}
//下载url的地图瓦片,并将之放到panel上
IEnumerator MapDownload(string url)
{
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url))
{
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
//获取下载的资产包
var texture = DownloadHandlerTexture.GetContent(uwr);
yield return texture;
GetComponent<Renderer>().material.mainTexture = texture;
}
}
}
//获取当前位置的url信息
IEnumerator StartGPS()
{
// Input.location 用于访问设备的位置属性(手持设备), 静态的LocationService位置
// LocationService.isEnabledByUser 用户设置里的定位服务是否启用
if (!Input.location.isEnabledByUser)
{
this.otherinfo = "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)
{
this.otherinfo = "Init GPS service time out";
yield return false;
}
if (Input.location.status == LocationServiceStatus.Failed)
{
this.otherinfo = "Unable to determine device location";
yield return false;
}
else
{
this.gps_info = Input.location.lastData.longitude + "," + Input.location.lastData.latitude;
this.otherinfo = " Time:" + Input.location.lastData.timestamp;
yield return new WaitForSeconds(100);
}
}
void StopGPS()
{
Input.location.Stop();
}
}
参考资料:《AR游戏:基于Unity 5的增强现实开发》
还有一个大佬写的文章~unity获取设备经纬度(unity使用GPS)详解