Json Geocode在C#中解析地址

时间:2014-09-22 12:16:41

标签: c# json google-maps

我想获得该位置的地址 我通过传递lat和long来使用谷歌地理编码来获取地址。

static readonly string RequestUrl = "http://maps.google.com/maps/api/geocode/json?";

/// <summary>
        /// Gets the raw object.
        /// </summary>
        /// <returns></returns>
protected JsonGeoData GetJsonObject() {

        StringBuilder url = new StringBuilder( GeoRequest.RequestUrl);

        if (this.Location != null) {
            url.AppendFormat("latlng={0}", this.Location.ToString());
        }
        else {
            url.AppendFormat("address={0}", HttpUtility.UrlEncode(this.Address));
        }
        url.AppendFormat("&sensor={0}", this.IsSensor.ToString().ToLower());
        if (!string.IsNullOrEmpty(this.Language))
            url.AppendFormat("&language={0}", HttpUtility.UrlEncode(this.Language));
        if(!string.IsNullOrEmpty(this.Region))
            url.AppendFormat("&region={0}", HttpUtility.UrlEncode(this.Region));

        WebRequest request = WebRequest.Create(url.ToString());
        using (WebResponse response = request.GetResponse()) {
            using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Deserialize<JsonGeoData>(reader.ReadToEnd());
            }
        }
    }



      /// <summary>
        /// Gets the response.
        /// </summary>
        /// <returns></returns>
        public GeoResponse GetResponse() {
            return new GeoResponse(this.GetJsonObject());
        }

 /// <summary cref="A">
        /// fetching location from web
        /// </summary>
        /// <typeparam name="T"></typeparam>
        private string getloc(double plat, double plng)
        {
            try
            {    
                GeoRequest objreq = new GeoRequest(plat, plng);
                GeoResponse objres = objreq.GetResponse();
                if (objres.Results.Count > 0)
                { return objres.Results[0].FormattedAddress; }
                else
                { return "Unknown"; }
            }
            catch (FormatException) { return "Unknown"; }
            catch (Exception)
            { return "Unknown"; }
        }

我试图从地理编码中获取json数据并使用序列化程序进行解析, 但是我收到错误&#39; sublocality_level_2不是GeoAddressType的有效值。&#39;

0 个答案:

没有答案