C#winform使用WebBrowser控件调用百度地图

C#winform使用WebBrowser控件调用百度地图

    • 一、申请百度地图密钥
    • 二、新建winform项目
    • 三、运行结果图如下:

一、申请百度地图密钥

百度官方文档:http://developer.baidu.com/map/jsmobile.htm
百度申请密钥:http://lbsyun.baidu.com/apiconsole/key
C#winform使用WebBrowser控件调用百度地图_第1张图片

二、新建winform项目

  1. 新建一个winform项目 ,打开VS2015,文件–>新建–>项目–>windows窗体应用程序;
    C#winform使用WebBrowser控件调用百度地图_第2张图片

2.设计界面
在Form1中添加label,textBox,button,webBrowser控件。WebBrowser 类使用户可以在窗体中导航网页。
C#winform使用WebBrowser控件调用百度地图_第3张图片

3.winform下添加HTML页面
右键 添加–>新建项–>HTML页
C#winform使用WebBrowser控件调用百度地图_第4张图片
C#winform使用WebBrowser控件调用百度地图_第5张图片
现在项目下有一个窗体Form1和一个HTML页,在HTMLPage1中添加代码,将您的密钥修改为一开始在百度地图申请的密钥AK。
HTMLPage1.html页代码




    
    
    
    
    //
    地图展示


    

http://lbsyun.baidu.com/jsdemo.htm#a1_2
百度官方文档给了很多Demo,可根据先不要进行选择
C#winform使用WebBrowser控件调用百度地图_第6张图片
4.Form1.cs文件代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;

namespace WindowsFormsApplication1
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]//调用JS代码必要
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                string str_url = Application.StartupPath + "../HTMLPage1.html";// 添加自己添加的html文件名,注意使用相对路径的方法 HTMLPage1.html要复制到debug目录下
                Uri url = new Uri(str_url);
                webBrowser1.Url = url;
                webBrowser1.ObjectForScripting = this;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //本地文件 MapWinForms\bin\Debug  
            string url = Application.StartupPath + "\\HTMLPage1.html";
            //textBox1.Text = url;
            url = textBox1.Text.ToString();
            //string file = "file:///E:\\WinFormBaiduMap\\a1_1.html";

            //屏蔽js相关错误  
            webBrowser1.ScriptErrorsSuppressed = true;

            //导航显示本地HTML文件  
            webBrowser1.Navigate(url);
        }
    }
}

三、运行结果图如下:

C#winform使用WebBrowser控件调用百度地图_第7张图片

你可能感兴趣的:(C#.net)