02
09/2014
c#通过谷歌地图API获得地区经纬度
c#通过谷歌地图API获得地区经纬度
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.IO;
using KangryUtils;
using System.Xml;
namespace CrawlerMonitor
{
class Geo
{
public static List<string> getLngAndLat(string locationName) {
List<string> lngAndLat = new List<string>();
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + HttpUtility.UrlDecode(locationName) + "&sensor=false";
string responseString = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://maps.google.com/maps/api/geocode/xml?address=" + HttpUtility.UrlDecode(locationName) + "&sensor=false");
request.Timeout = 30 * 1000;
request.Method = "GET";
request.Accept = "*/*";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sdr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseString = sdr.ReadToEnd();
sdr.Close();
response.Close();
}
catch (Exception e)
{
common.LOG.errorLog("Failed to get data from " + url + ". " + e.Message);
}
if (responseString != "")
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseString);
try
{
string lat = doc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat").InnerText;
string lng = doc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng").InnerText;
lngAndLat.Add(lng);
lngAndLat.Add(lat);
}
catch (Exception e)
{
common.LOG.errorLog("Failed to get lng and lat from string: "+responseString+". "+ e.Message);
}
}
return lngAndLat;
}
}
}转载请注明:康瑞部落 » c#通过谷歌地图API获得地区经纬度

0 条评论