setpoint.html:行政區域工具 用Winform 讀取百度地圖的經緯度:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Dra....
setpoint.html:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>行政區域工具</title> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.4"></script> </head> <body> <div style="width:520px;height:340px;border:1px solid gray" id="container"></div> <p><input id="startBtn" type="button" onclick="startTool();" value="開啟取點工具" /><input type="button" onclick="map.clearOverlays();document.getElementById('info').innerHTML = '';points=[];" value="清除" /></p> <div id="info"></div> <div id="lng"></div> <div id="lat"></div> </body> </html> <script type="text/javascript"> var map = new BMap.Map("container"); // 創建Map實例 map.centerAndZoom("北京", 11); // 初始化地圖,設置中心點坐標和地圖級別 map.addControl(new BMap.NavigationControl()); map.addControl(new BMap.ScaleControl()); var key = 1; //開關 var newpoint; //一個經緯度 var points = []; //數組,放經緯度信息 var polyline = new BMap.Polyline(); //折線覆蓋物 function startTool(){ //開關函數 if(key==1){ document.getElementById("startBtn").style.background = "green"; document.getElementById("startBtn").style.color = "white"; document.getElementById("startBtn").value = "開啟狀態"; key=0; } else{ document.getElementById("startBtn").style.background = "red"; document.getElementById("startBtn").value = "關閉狀態"; key=1; } } map.addEventListener("click",function(e){ //單擊地圖,形成折線覆蓋物 newpoint = new BMap.Point(e.point.lng,e.point.lat); if(key==0){ // if(points[points.length].lng==points[points.length-1].lng){alert(111);} points.push(newpoint); //將新增的點放到數組中 polyline.setPath(points); //設置折線的點數組 map.addOverlay(polyline); //將折線添加到地圖上 document.getElementById("info").innerHTML += "new BMap.Point(" + e.point.lng + "," + e.point.lat + "),</br>"; //輸出數組裡的經緯度 document.getElementById("lng").innerHTML= e.point.lng; document.getElementById("lat").innerHTML= e.point.lat; } }); map.addEventListener("dblclick",function(e){ //雙擊地圖,形成多邊形覆蓋物 if(key==0){ map.disableDoubleClickZoom(); //關閉雙擊放大 var polygon = new BMap.Polygon(points); map.addOverlay(polygon); //將折線添加到地圖上 } }); </script>
用Winform 讀取百度地圖的經緯度:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Security.Permissions; namespace baidudemo { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] [System.Runtime.InteropServices.ComVisibleAttribute(true)] public partial class Form2 : Form { /// <summary> /// /// </summary> public Form2() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form2_Load(object sender, EventArgs e) { string str_url = Application.StartupPath + "\\baidu\\setpoint.html"; Uri url = new Uri(str_url); webBrowser1.Url = url; webBrowser1.ObjectForScripting = this; } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { string tag_lng = webBrowser1.Document.GetElementById("lng").InnerText; string tag_lat = webBrowser1.Document.GetElementById("lat").InnerText; this.textBox1.Text = tag_lat; this.textBox2.Text = tag_lng; } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void webBrowser1_LocationChanged(object sender, EventArgs e) { ; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Web; using System.Web.Script.Serialization; //引用System.Web.Extensions using System.Data; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Runtime.Serialization.Formatters;
/// <summary> /// /// </summary> public class JsonHelper { //對應JSON的singleInfo成員 public string singleInfo = string.Empty; protected string _error = string.Empty; protected bool _success = true; protected long _totalCount = 0; protected System.Collections.ArrayList arrData = new ArrayList(); protected System.Collections.ArrayList arrDataItem = new ArrayList(); public JsonHelper() { // //TODO: 在此處添加構造函數邏輯 // } //對應於JSON的success成員 public bool success { get { return _success; } set { //如設置為true則清空error if (success) _error = string.Empty; _success = value; } } //對應於JSON的error成員 public string error { get { return _error; } set { //如設置error,則自動設置success為false if (value != "") _success = false; _error = value; } } public long totlalCount { get { return _totalCount; } set { _totalCount = value; } } //重置,每次新生成一個json對象時必須執行該方法 public void Reset() { _success = true; _error = string.Empty; singleInfo = string.Empty; arrData.Clear(); arrDataItem.Clear(); } public void AddItem(string name, string value) { arrData.Add("/" + name + "/:" + "/" + value + "/"); } public void ItemOk() { arrData.Add("<BR>"); //返回總記錄條數 totlalCount++; } //序列化JSON對象,得到返回的JSON代碼 public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("{"); sb.Append("/totalCount/:/" + _totalCount.ToString() + "/,"); sb.Append("/success/:" + _success.ToString().ToLower() + "/,"); sb.Append("/error/:/" + _error.Replace("/", "///") + "/,"); sb.Append("/data/:/["); int index = 0; sb.Append("{"); if (arrData.Count <= 0) { sb.Append("}"); } else { foreach (string val in arrData) { index++; if (val != "<BR>") { sb.Append(val + ","); } else { sb = sb.Replace(",", "", sb.Length - 1, 1); sb.Append("},"); if (index < arrData.Count) { sb.Append("{"); } } } sb = sb.Replace(",", "", sb.Length - 1, 1); sb.Append("]"); } sb.Append("}"); return sb.ToString(); } public string ToSingleString() { StringBuilder sb = new StringBuilder(); sb.Append("{"); sb.Append("success:" + _success.ToString().ToLower() + ","); sb.Append("data:"); int index = 0; sb.Append("{"); if (arrData.Count <= 0) { sb.Append("}"); } else { foreach (string val in arrData) { index++; if (val != "<BR>") { sb.Append(val + ","); } else { sb = sb.Replace(",", "", sb.Length - 1, 1); sb.Append("},"); if (index < arrData.Count) { sb.Append("{"); } } } sb = sb.Replace(",", "", sb.Length - 1, 1); sb.Append(""); } sb.Append("}"); return sb.ToString(); } public static string ObjectToJSON(object obj) { JavaScriptSerializer jss =new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch(Exception ex) { throw new Exception("JSONHelper.ObjectToJSON(): "+ ex.Message); } } public static List<Dictionary<string,object>>DataTableToList(DataTable dt) { List<Dictionary<string,object>> list=new List<Dictionary<string,object>>(); foreach(DataRow dr in dt.Rows) { Dictionary<string,object> dic =new Dictionary<string,object>(); foreach(DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName]); } list.Add(dic); } return list; } /// <summary> /// /// </summary> /// <param name="ds"></param> /// <returns></returns> public static Dictionary<string,List<Dictionary<string,object>>>DataSetToDic(DataSet ds) { Dictionary<string,List<Dictionary<string,object>>> result =new Dictionary<string,List<Dictionary<string,object>>>(); foreach(DataTable dt in ds.Tables) result.Add(dt.TableName,DataTableToList(dt)); return result; } /// <summary> /// /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string DataTableToJSON(DataTable dt) { return ObjectToJSON(DataTableToList(dt)); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonText"></param> /// <returns></returns> public static T JSONToObject<T>(string jsonText) { JavaScriptSerializer jss =new JavaScriptSerializer(); try { return jss.Deserialize<T>(jsonText); } catch(Exception ex) { throw new Exception("JSONHelper.JSONToObject(): "+ ex.Message); } } /// <summary> /// /// </summary> /// <param name="jsonText"></param> /// <returns></returns> public static Dictionary<string,List<Dictionary<string,object>>>TablesDataFromJSON(string jsonText) { return JSONToObject<Dictionary<string,List<Dictionary<string,object>>>>(jsonText); } /// <summary> /// /// </summary> /// <param name="jsonText"></param> /// <returns></returns> public static Dictionary<string,object>DataRowFromJSON(string jsonText) { return JSONToObject<Dictionary<string,object>>(jsonText); } public static string ToJsJson(object item)//參數要裝換成JSON的對象 { DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); using(MemoryStream ms=new MemoryStream()) { serializer.WriteObject(ms, item); StringBuilder sb = new StringBuilder(); sb.Append(Encoding.UTF8.GetString(ms.ToArray())); return sb.ToString(); } } //反序列化 //T指定要序列化的對象,jsonString是JSON字元串變數 public static T FromJsonTo<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { T jsonObject = (T)ser.ReadObject(ms); return jsonObject; } } }
/// <summary> /// 提供 Http 相關方法。 /// </summary> public class HttpUtils { /// <summary> /// 執行HTTP GET請求。 /// </summary> /// <param name="url">請求地址</param> /// <param name="parameters">請求參數</param> /// <returns>HTTP響應</returns> public static string DoGet(string url, IDictionary<string, string> parameters) { if (parameters != null && parameters.Count > 0) { if (url.Contains("?")) { url = url + "&" + BuildPostData(parameters); } else { url = url + "?" + BuildPostData(parameters); } } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ServicePoint.Expect100Continue = false; req.Method = "GET"; req.KeepAlive = true; req.UserAgent = "Test"; req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; HttpWebResponse rsp = null; try { rsp = (HttpWebResponse)req.GetResponse(); } catch (WebException webEx) { if (webEx.Status == WebExceptionStatus.Timeout) { rsp = null; } } if (rsp != null) { if (rsp.CharacterSet != null) { Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); return GetResponseAsString(rsp, encoding); } else { return string.Empty; } } else { return string.Empty; } } /// <summary> /// 把響應流轉換為文本。 /// </summary> /// <param name="rsp">響應流對象</param> /// <param name="encoding">編碼方式</param> /// <returns>響應文本</returns> private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { StringBuilder result = new StringBuilder(); Stream stream = null; StreamReader reader = null; try { // 以字元流的方式讀取HTTP響應 stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); // 每次讀取不大於256個字元,並寫入字元串 char[] buffer = new char[256]; int readBytes = 0; while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0) { result.Append(buffer, 0, readBytes); } } catch (WebException webEx) { if (webEx.Status == WebExceptionStatus.Timeout) { result = new StringBuilder(); } } finally { // 釋放資源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } return result.ToString(); } /// <summary> /// 組裝普通文本請求參數。 /// </summary> /// <param name="parameters">Key-Value形式請求參數字典。</param> /// <returns>URL編碼後的請求數據。</returns> private static string BuildPostData(IDictionary<string, string> parameters) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator(); while (dem.MoveNext()) { string name = dem.Current.Key; string value = dem.Current.Value; // 忽略參數名或參數值為空的參數 if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value)) { if (hasParam) { postData.Append("&"); } postData.Append(name); postData.Append("="); postData.Append(Uri.EscapeDataString(value)); hasParam = true; } } return postData.ToString(); } /* GoBack():後退 GoForward():前進 Refresh():刷新 Stop():停止 GoHome():瀏覽主頁 WebBrowser控制項的常用屬性: Document:獲取當前正在瀏覽的文檔 DocumentTitle:獲取當前正在瀏覽的網頁標題 StatusText:獲取當前狀態欄的文本 Url:獲取當前正在瀏覽的網址的Uri ReadyState:獲取瀏覽的狀態 WebBrowser控制項的常用事件: DocumentTitleChanged, CanGoBackChanged, CanGoForwardChanged, DocumentTitleChanged, ProgressChanged, ProgressChanged */ /// <summary> /// 根據Name獲取元素 /// </summary> /// <param name="wb"></param> /// <param name="Name"></param> /// <returns></returns> public HtmlElement GetElement_Name(WebBrowser wb, string Name) { HtmlElement e = wb.Document.All[Name]; return e; } /// <summary> /// 根據Id獲取元素 /// </summary> /// <param name="wb"></param> /// <param name="id"></param> /// <returns></returns> public HtmlElement GetElement_Id(WebBrowser wb, string id) { HtmlElement e = wb.Document.GetElementById(id); return e; } /// <summary> /// 根據Index獲取元素 /// </summary> /// <param name="wb"></param> /// <param name="index"></param> /// <returns></returns> public HtmlElement GetElement_Index(WebBrowser wb, int index) { HtmlElement e = wb.Document.All[index]; return e; } /// <summary> /// 獲取form表單名name,返回表單 /// </summary> /// <param name="wb"></param> /// <param name="form_name"></param> /// <returns></returns> public HtmlElement GetElement_Form(WebBrowser wb, string form_name) { HtmlElement e = wb.Document.Forms[form_name]; return e; } /// <summary> /// 設置元素value屬性的值 /// </summary> /// <param name="e"></param> /// <param name="value"></param> public void Write_value(HtmlElement e, string value) { e.SetAttribute("value", value); } /// <summary> /// 執行元素的方法,如:click,submit(需Form表單名)等 /// </summary> /// <param name="e"></param> /// <param name="s"></param> public void Btn_click(HtmlElement e, string s) { e.InvokeMember(s); } }