unity获取地理位置
因为项目功能需要,需要获取用户当前的位置信息,百度了一下,很多资料,发现都不能满足直自己的需求。于是整合了网上的资料,才满足自己的需求,说说需求吧:需要定位到玩家具体位置,具体到街道信息。
获取经纬度
获取经纬的方式我使用自带API, 官方说明;http://docs.unity3d.com/Documentation/ScriptReference/LocationService.Start.html
几个重要的参数;
- isEnabledByUser – 检测用户设置里的定位服务是否启用(首次会弹出提示,询问用户是否同意。如果不同意,定位会失败)
- lastData – 最近一次测量的地理位置(LocationInfo lastData; 也就是要和 LocationInfo 关联了)
- status – 定位服务的状态
- 其他属性,自行看文档,毕竟看官方文档是我们学习知识最好和最快的方式之一,
代码如下
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"}