首页 > 解决方案 > 反向地理位置未返回正确的国家/地区名称

问题描述

我正在使用 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;
            }
         };

    }

我已经厌倦了俄罗斯境内的几个地点,它只输出数字。我不知道其他国家是否会发生这种情况,但我尝试过的其他国家都可以正常工作并输出国家名称。

标签: c#androidgoogle-mapsunity3dreverse-geocoding

解决方案


将格式化的地址解析为字符串并不是获取国家名称的最佳方法,因为正如您所发现的,俄罗斯地址以邮政编码结尾。国家名称address_components作为单独的对象提供。

你想检索results.address_components[].long_namewhere typesis [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"
}

推荐阅读