/// <summary>
/// 百度API从经纬度坐标到地址的转换服务
/// </summary>
/// <param name="lng"></param>
/// <param name="lat"></param>
/// <returns></returns>
public string GetAddress(string lng, string lat)
{
string strUrl = @"http://api.map.baidu.com/geocoder/v2/?ak=ELYtYXEH1WmDrK1wDsEWRNkGviRL0ZEo&callback=renderReverse&location=" + lat + "," + lng + @"&output=json&pois=0";
//WebRequest request = WebRequest.Create(url);
//request.Method = "POST";
//XmlDocument xmlDoc = new XmlDocument();
//string sendData = xmlDoc.InnerXml;
//byte[] byteArray = Encoding.Default.GetBytes(sendData);
//Stream dataStream = request.GetRequestStream();
//dataStream.Write(byteArray, 0, byteArray.Length);
//dataStream.Close();
//WebResponse response = request.GetResponse();
//dataStream = response.GetResponseStream();
//StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("utf-8"));
string strResult;
try
{
WebRequest request = WebRequest.Create(strUrl);
request.Timeout = 12000;
request.Method = "POST";
HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
Stream myStream = HttpWResp.GetResponseStream();
StreamReader reader = new StreamReader(myStream,System.Text.Encoding.GetEncoding("utf-8"));
strResult = reader.ReadToEnd();
//StringBuilder strBuilder = new StringBuilder();
//while (-1 != reader.Peek())
//{
// strBuilder.Append(reader.ReadLine());
//}
//strResult = strBuilder.ToString();
}
catch (Exception exp)
{
strResult = "错误:" + exp.Message;
}
return strResult;
}
解析百度API返回的Json串方法如下:
#region 解析Json
//调用百度API接口
string strJosn = GetAddress(reservation.Longitude.ToString(), reservation.Latitude.ToString());
strJosn = strJosn.Remove(strJosn.Length - 1).Remove(0, 29);
JObject jo = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(strJosn);
string Status = jo["status"].ToString();
if (Status == "0")
{
//地址拼接
strJosn = jo["result"]["formatted_address"].ToString() + jo["result"]["sematic_description"].ToString();
}
else if (Status == "1")
{
result.IsSuccess = false;
result.MsgCode = "0";
result.Message = "服务器内部错误!";
}
else if (Status == "2")
{
result.IsSuccess = false;
result.MsgCode = "0";
result.Message = "请求参数非法!";
}
else if (Status == "101")
{
result.IsSuccess = false;
result.MsgCode = "0";
result.Message = "服务禁用!";
}
#endregion