点点滴滴的积累

yanchao

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
最近一个项目需要拿到一地地理位置的 经纬度 总不能在google earth上一个个找吧
于是希望可以找到相应的web service 发现以前的msn search 支持 现在 也不支持了 发现这些地理信息的服务 都仅限于你在你的网站上嵌入一个 地图 然后你可以在他的地图上 添加什么东西   SDK都是基于javascript的 没有完全的开放啊
后来实在没有办法了 想到 google map可以输入地址 然后定位到那个区域 那么 这其中拿到的结果一定有经纬度的信息 于是 在google query了一个 然后view source了一下 发现 果不其然 这个经纬度信息 是明文放在网页里面的
 所以 采用以下办法就可以了

class Getgeo
{
public struct geo
{
public string Latitude;
public string Longtitude;
}

public static geo Getgeo(
string location)
{

string geo="";
geo mygeo = new geo();
string results = String.Empty;
HttpWebRequest searchRequest =
(HttpWebRequest)WebRequest.Create(@"http://maps.google.com/maps?f=q&geocode=&q="+location +"&output=js");
WebResponse myresponse = searchRequest.GetResponse();
Stream responseStream = myresponse.GetResponseStream();
byte[] buffer = new byte[9999 ];
responseStream.Read(buffer, 0, (int)9999);
results = System.Text.Encoding.ASCII.GetString(buffer);
System.Text.RegularExpressions.Regex myregex = new Regex(@"center..lat\:[^,]+,lng\:.{0,1}[0-9]+.[0-9]+");
MatchCollection mc = myregex.Matches(results);

foreach (Match mymatch in mc)
{
geo = mymatch.Value;
string latitude=geo .Substring (geo .IndexOf ("lat:")+4,5);
string longtitude=geo .Substring (geo .IndexOf ("lng:")+4,5);

mygeo.Latitude = latitude;
mygeo.Longtitude = longtitude;
if (mygeo.Latitude == null)
{
System.Windows.Forms.MessageBox.Show("Null seen");
}
}
myresponse.Close();

responseStream.Close();

myresponse.Close();
return mygeo;
}

public static string GetLongtitude(
string location)
{

geo mygeo = Getgeo(location );
return mygeo.Longtitude;

}


public static string GetLatitude(
string location)
{
geo mygeo = Getgeo(location );
return mygeo.Latitude;

}
}


具体说来就是http://maps.google.com/maps?f=q&geocode=&q="+你要查找的位置+"&output=js" 的httprequest 然后在得到的字符串里面 匹配一下  (@"center..lat\:[^,]+,lng\:.{0,1}[0-9]+.[0-9]+") 正则表达式就可以啦
posted on 2008-02-23 21:26  yanchao  阅读(15752)  评论(3编辑  收藏  举报