最近項目需要通過經緯度查詢 具體的地址和區域名稱,通過查詢網絡資源,發現提供的大多是得到具體的地址而對區域或城市名稱的獲取就不是很好把握;在這裡自己搞了個:
代碼如下:
//webclient客戶端對象
WebClient client = new WebClient();
string url = "http://maps.google.com/maps/api/geocode/xml?latlng=" + latitude + "," + longitude + "&language=zh-CN&sensor=false";//請求地址
client.Encoding = Encoding.UTF8;//編碼格式
string responseTest = client.DownloadString(url);
//下載xml響應數據
string address = "";//返回的地址
XmlDocument doc = new XmlDocument();
//創建XML文檔對象
if (!string.IsNullOrEmpty(responseTest))
{
doc.LoadXml(responseTest);//加載xml字符串
//查詢狀態信息
string xpath = @"GeocodeResponse/status";
XmlNode node = doc.SelectSingleNode(xpath);
string status = node.InnerText.ToString();
if (status == "OK") {
//查詢詳細地址信息
xpath = @"GeocodeResponse/result/formatted_address";
node = doc.SelectSingleNode(xpath);
address = node.InnerText.ToString();
//查詢地區信息
XmlNodeList nodeListAll = doc.SelectNodes("GeocodeResponse/result");
XmlNode idt = nodeListAll[0];
XmlNodeList idts = idt.SelectNodes("address_component[type='sublocality']");
//address_component[type='sublocality']表示篩選type='sublocality'的所有相關子節點;
XmlNode idtst = idts[0];
string area = idtst.SelectSingleNode("short_name").InnerText;
address = address + "," + area;
}
}
address就是獲取到的具體地址信息和區域信息;