c# - 反向地理位置未返回正确的国家/地区名称
问题描述
我正在使用 Google Maps Reverse Geolocation 在 Unity 中查找输入的纬度和经度的国家名称。
我已经通过 Inspector 输入来自世界各地的位置来测试代码。每次输出国家名称(如英国、美国、法国、新加坡等)。但是,当我输入俄语经纬度时,它只返回一个数字。这个数字原来是该地区的邮政编码。
这是我正在使用的代码:
private string GoogleAPIKey = "MY KEY";
public string latitude;
public string longitude;
private string countryLocation;
public Text console;
IEnumerator Start()
{
if (!Input.location.isEnabledByUser){
yield break;
}
Input.location.Start();
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
if (maxWait < 1)
{
yield break;
}
if (Input.location.status == LocationServiceStatus.Failed)
{
yield break;
}
else
{
longitude = Input.location.lastData.longitude.ToString();
latitude = Input.location.lastData.latitude.ToString();
console.text += (latitude + " " + longitude);
}
Input.location.Stop();
using (WWW www = new WWW("https://maps.googleapis.com/maps/api/geocode/json?latlng=" +latitude +","+ longitude + "&key=" + GoogleAPIKey)){
yield return www;
if(www.error == null)
{
var location = Json.Deserialize(www.text) as Dictionary<string, object>;
var locationList = location["results"] as List<object>;
var locationListing = locationList[0] as Dictionary<string, object>;
countryLocation = locationListing["formatted_address"].ToString().Substring(locationListing["formatted_address"].ToString().LastIndexOf(",")+2);
console.text += (" LOCATION IS: " + countryLocation.ToString());
}else{
console.text += www.error;
}
};
}
我已经厌倦了俄罗斯境内的几个地点,它只输出数字。我不知道其他国家是否会发生这种情况,但我尝试过的其他国家都可以正常工作并输出国家名称。
解决方案
将格式化的地址解析为字符串并不是获取国家名称的最佳方法,因为正如您所发现的,俄罗斯地址以邮政编码结尾。国家名称address_components
作为单独的对象提供。
你想检索results.address_components[].long_name
where types
is [country, political]
。
这是显示国家对象的简短响应:
{
"plus_code": {
"compound_code": "9XMF+9P Yegoryevsk, Moscow Oblast, Russia",
"global_code": "9G7W9XMF+9P"
},
"results": [
{
"address_components": [
{
"long_name": "Russia",
"short_name": "RU",
"types": [
"country",
"political"
]
}
],
"formatted_address": "Unnamed Road, Moskovskaya oblast', Russia, 140301",
}
],
"status": "OK"
}
推荐阅读
- spring-boot - 使用 SpringBoot 的 Apache Camel RabbitMQ 新 URI 格式的连接被拒绝问题
- c# - 如何为 DataGridViewCheckBoxColumn 提供初始值并修复错误对象引用未设置为对象的实例?
- ios - 如何使用枚举获取字符串值
- java - How to re-use method and add different variables and if statements?
- python - 制作一个计算每个列表中负数的python代码?
- python - Unable to find elements after switching to iframe in Selenium python
- ios - Dependency caching on Jenkins similar to CircleCI
- html - Why does refreshing an anchor link / trying to go directly to an anchor link go to the top of the page?
- javascript - Can't bind multiple parameters to the request's content
- php - 删除 php 中的 html、head 和 body 标签