C# winform窗体使用WebBrowser控件显示百度地图
1、效果展示
2、创建winfrom窗体应用程序,项目结构如下:
3、点开MapForm窗体,添加WebBroswer控件
4、主要代码
4.1、map.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="css/map.css"/>
<title>地图展示</title>
</head>
<body>
<div id="map"></div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=密钥"></script>
<script type="text/javascript" src="js/map.js"></script>
</body>
</html>
4.2、map.js
var App = function () {
this.Setup = function () {
this.InitMap();
};
this.InitMap = function () {
// 创建Map实例
this.Map = new BMap.Map("map");
// 初始化地图,设置中心点和地图级别
this.Map.centerAndZoom(new BMap.Point("118.38", "31.33"), 11);
// 地图加入比例尺控件
this.Map.addControl(new BMap.ScaleControl());
// 地图类型控件
this.Map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] }));
// 开启鼠标滚轮缩放
this.Map.enableScrollWheelZoom();
};
}
$(document).ready(function () {
var app = new App();
app.Setup();
});
4.3、map.css
body, html, #map {
width: 100%;
height: 100%;
overflow: hidden;
margin: 0;
font-family: "微软雅黑";
}
4.4、在窗体启动的时候加载我们写好的html文件
using System;
using System.Windows.Forms;
namespace TestBaiDuMap
{
public partial class BaiDuMapForm : Form
{
public BaiDuMapForm()
{
InitializeComponent();
Browser.Url = new Uri(@"E:\Code\C#\Test\TestBaiDuMap\TestBaiDuMap\BaiDuMap\map.html");
}
}
}
5、设置WebBroswer控件在父容器中停靠,设置Anchor,这样在拖动窗体地图不会变形