码迷,mamicode.com
首页 > Web开发 > 详细

csharp: WebBrowser read baidumap

时间:2016-01-04 18:12:16      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

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);
        }
    }

  

csharp: WebBrowser read baidumap

标签:

原文地址:http://www.cnblogs.com/geovindu/p/5099819.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!