C# WebRequest to Google Geocoding API 返回的结果与浏览器不同



我对谷歌地理编码网络服务有一个非常奇怪的问题。我想在我的 c# 项目中使用它来对输入的地址服务器端进行地理编码。到目前为止一切顺利,但我遇到了一个不想以这种方式进行地理编码的地址。我测试的所有其他地址(甚至是中文地址(都返回与谷歌地图本身相同的结果。

这是我的基本准则:

HttpWebRequest request = WebRequest.Create(@"http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=Gerdestr.%2B1%2C%2B58454%2C%2BWitten%2C%2BGermany&components=country:Germany") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseContent = reader.ReadToEnd().Trim();

url字符串实际上是由代码生成的,但这是困扰我的。这是一个现有的德语地址,但我得到的结果是:

{
"results" : [
      {
         "address_components" : [
            {
               "long_name" : "Germany",
               "short_name" : "DE",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Germany",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 55.058347,
                  "lng" : 15.0418962
               },
               "southwest" : {
                  "lat" : 47.2701115,
                  "lng" : 5.8663425
               }
            },
            "location" : {
               "lat" : 51.165691,
               "lng" : 10.451526
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 55.058347,
                  "lng" : 15.0418962
               },
               "southwest" : {
                  "lat" : 47.2701115,
                  "lng" : 5.8663425
               }
            }
         },
         "partial_match" : true,
         "place_id" : "ChIJa76xwh5ymkcRW-WRjmtd6HU",
         "types" : [ "country", "political" ]
      }
   ],
   "status" : "OK"
}

它有点笼统,适合德国的每个地址^^。

奇怪的是,当我在浏览器中使用相同的字符串时,它会返回正确的结果。这就像地址参数为空,但如您所见,它不是。

有什么想法吗?我没了。感谢每一个帮助!

我认为您的请求中有错字。街道名称应为"gerdesstr."。

如果以略有不同的顺序提供地址信息,则地理编码 api 可以更正此错误:

HttpWebRequest request = WebRequest.Create(@"http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=1+Gerdestr.,+58454+Witten,+Germany") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseContent = reader.ReadToEnd().Trim();

来源: https://developers.google.com/maps/documentation/geocoding/

最新更新