2011年4月7日 星期四

C# .Net 與 Google Map 地址定位取回經緯度

//設定 GoogleMapKey
string apikey = System.Configuration.ConfigurationManager.AppSettings["GoogleMapKey"].ToString();
string url = "http://maps.google.com.tw/maps/geo?q=" + Address + "&output=xml&key=" + apikey + "&sensor=false";
WebRequest myrequest = WebRequest.Create(url);

System.Net.WebResponse mywebresponse = myrequest.GetResponse();
Stream mystream = mywebresponse.GetResponseStream();
//讀取定位結果資料
StreamReader sr = new System.IO.StreamReader(mystream, System.Text.Encoding.UTF8);
string XmlText = sr.ReadToEnd();
int index1 = XmlText.IndexOf("coordinates");
int index2 = XmlText.IndexOf("</coordinates>");
string Point = XmlText.Substring(index1 + 12, index2 - index1 - 12);
//解析出 Longitude
Longitude = Point.Substring(0, Point.IndexOf(","));
//解析出 Latitude
Latitude = Point.Substring(Point.IndexOf(",") + 1, Point.LastIndexOf(",") - Point.IndexOf(",") - 1);

using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RMSDBConnection"].ToString()))
{
con.Open();
//更新Map_X , Map_Y
using (SqlCommand commandU = new SqlCommand("Update Object Set Map_X = @Map_X, Map_Y = @Map_Y where ObjectID = @ObjectID", con))
{
commandU.Parameters.Add(new SqlParameter("Map_X", Longitude));
commandU.Parameters.Add(new SqlParameter("Map_Y", Latitude));
commandU.Parameters.Add(new SqlParameter("ObjectID", ObjectID));
commandU.ExecuteNonQuery();
}
con.Close();
}

沒有留言:

張貼留言