c#调用百度地图API实现标点和连接数据库实现弹窗
最终效果
你需要准备
- 数据库
- 秘钥(网上教程较多,也可以使用别人的秘钥)
http://lbsyun.baidu.com/index.php?title=jspopular
代码部分
c#代码
using System;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Configuration;
using System.Security.Permissions; //为了能与JS交互
using System.IO;
namespace Map
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//try
//{
// //这个文件与可执行文件放在同一目录
webBrowser1.Url = new Uri(Path.Combine(Application.StartupPath, "marker.html"));
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
string conStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;//连接数据库的语句,次方法需要在App.config里面配置
OdbcConnection conn = new OdbcConnection(conStr);
conn.Open();
string mysql = "SELECT * FROM Condition_Monitoring where SIM in(select SIM from Basic_Info)ORDER BY Upload_Time DESC LIMIT 3"; //查询出符合条件的最近的一条数据
OdbcDataAdapter adapter = new OdbcDataAdapter(mysql, conStr);
System.Data.DataTable dt = new System.Data.DataTable("Condition_Monitoring");
adapter.Fill(dt);
conn.Close();
if (dt.Rows.Count == 0) return;
//获取数据库数据
string[] sim = new string[dt.Rows.Count];
float[] dos = new float[dt.Rows.Count];
float[] lon = new float[dt.Rows.Count];
float[] lat = new float[dt.Rows.Count];
float[] tem = new float[dt.Rows.Count]; //温度
float[] hum = new float[dt.Rows.Count]; //湿度
string[] dum = new string[dt.Rows.Count]; //剩余电量
string[] pow = new string[dt.Rows.Count]; //供电类型
for (int i = 0; i < dt.Rows.Count; i++) //针对DataTable循环对数组赋值
{
sim[i] = dt.Rows[i][0].ToString();
dos[i] = float.Parse(dt.Rows[i][1].ToString());
lon[i] = float.Parse(dt.Rows[i][2].ToString());
lat[i] = float.Parse(dt.Rows[i][3].ToString());
tem[i] = float.Parse(dt.Rows[i][4].ToString());
hum[i] = float.Parse(dt.Rows[i][5].ToString());
dum[i] = dt.Rows[i][6].ToString();
pow[i] = dt.Rows[i][7].ToString();
object[] obj = new object[] { sim[i], dos[i], lon[i], lat[i], tem[i], hum[i], dum[i], pow[i] };
webBrowser1.Document.InvokeScript("setLocation", obj);
}
}
/// <summary>
/// 触发标点以及显示窗口
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
string conStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
OdbcConnection conn = new OdbcConnection(conStr);
conn.Open();
string mysql = "SELECT * FROM Condition_Monitoring where SIM in(select SIM from Basic_Info)ORDER BY Upload_Time DESC LIMIT 3"; //查询出符合条件的最近的一条数据
OdbcDataAdapter adapter = new OdbcDataAdapter(mysql, conStr);
System.Data.DataTable dt = new System.Data.DataTable("Condition_Monitoring");
adapter.Fill(dt);
conn.Close();
if (dt.Rows.Count == 0) return;
//获取数据库数据
string[] sim = new string[dt.Rows.Count];
float[] dos = new float[dt.Rows.Count];
float[] lon = new float[dt.Rows.Count];
float[] lat = new float[dt.Rows.Count];
float[] tem = new float[dt.Rows.Count]; //温度
float[] hum = new float[dt.Rows.Count]; //湿度
string[] dum = new string[dt.Rows.Count]; //剩余电量
string[] pow = new string[dt.Rows.Count]; //供电类型
for (int i = 0; i < dt.Rows.Count; i++) //针对DataTable循环对数组赋值
{
sim[i] = dt.Rows[i][0].ToString();
dos[i] = float.Parse(dt.Rows[i][1].ToString());
lon[i] = float.Parse(dt.Rows[i][2].ToString());
lat[i] = float.Parse(dt.Rows[i][3].ToString());
tem[i] = float.Parse(dt.Rows[i][4].ToString());
hum[i] = float.Parse(dt.Rows[i][5].ToString());
dum[i] = dt.Rows[i][6].ToString();
pow[i] = dt.Rows[i][7].ToString();
object[] obj = new object[] { sim[i], dos[i], lon[i], lat[i], tem[i], hum[i], dum[i], pow[i] };
webBrowser1.Document.InvokeScript("setLocation", obj);
}
}
}
}
JavaScript部分(HTML)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello World</title>
<style type="text/css">
//对网页以及信息窗口宽度高度等设置
body, html, #allmap {
width: 100%;
height: 100%;
overflow: hidden;
margin: 0;
}
#l-map {
height: 100%;
width: 78%;
float: left;
border-right: 2px solid #bcbcbc;
}
#r-result {
height: 100%;
width: 20%;
float: left;
}
.info_ul {
margin: 0 0 5px 0;
padding: 0.2em 0;
}
.info_li {
line-height: 26px;
font-size: 15px;
}
.info_span {
width: 80px;
display: inline-block;
}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ttv8Mf0FOSR9iife0kfxS0iIvBwuHzzA"></script>
ak后面这一串是需要自己申请的秘钥
</head>
<body>
<div id="allmap">
</div>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("allmap"); // 创建Map实例,打开地图时默认加载的
var point = new BMap.Point(103.388611,35.563611); // 创建点坐标,此为兰州交通大学初始坐标
map.centerAndZoom(point, 6); // 初始化地图,设置中心点坐标和地图大小级别
map.addControl(new BMap.NavigationControl()); // 添加平移缩放控件
map.addControl(new BMap.ScaleControl()); // 添加比例尺控件
map.addControl(new BMap.OverviewMapControl()); //添加缩略地图控件
map.addControl(new BMap.MapTypeControl()); //添加地图类型控件
map.setCurrentCity("湖北"); //设置地图显示的城市,这个不知道有啥用
map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
//这个setlocation是自己定义的函数,需要显示哪些数,就在括号里添加几个,然后里面当做变量使用,和c#里的object数组一一对应
function setLocation(sim,dos,lng,lat, tem, hum, dum, pow){
map.removeOverlay(marker);
var point = new BMap.Point(lng,lat);
map.centerAndZoom(point, 6); //设置查询位置结束显示时地图大小级别,数值越大,放大倍数越大(越详细)
var marker=new BMap.Marker(point);
map.addOverlay(marker); //将标注添加到地图中
//给标注点添加点击事件。使用立即执行函数和闭包
(function() {
var thePoint = point;
marker.addEventListener("click",function(){
showInfo(this,thePoint);
});
})();
function showInfo(thisMaker,point){ //显示信息窗口,显示标注点的信息。
var sContent =
'<ul class="info_ul">'
+'<li class="info_li">'
+'<span class="info_span">SIM卡号:</span> '+sim+' </li>'
+'<li class="info_li">'
+'<span class="info_span">剂量:</span> '+dos+' </li>'
+'<li class="info_li">'
+'<span class="info_span">温度:</span> '+tem+' </li>'
+'<li class="info_li">'
+'<span class="info_span">湿度:</span> '+hum+' </li>'
+'<li class="info_li">'
+'<span class="info_span">剩余电量:</span> '+dum+' </li>'
+'<li class="info_li">'
+'<span class="info_span">供电类型:</span> '+pow+' </li>'
+'</ul>';
var infoWindow = new BMap.InfoWindow(sContent); // 创建信息窗口对象
thisMaker.openInfoWindow(infoWindow); //图片加载完毕重绘infowindow
}
}
</script>
注意事项(参考以上代码段食用)
1
mark.html为JavaScript的代码文件,此文件放在 bin\Debug文件夹下
关于这个文件,可以新建文本文档,把代码复制到里面,另存为,名称填写“mark.html”,保存类型为“所有文件”。
2
为了与js交互,需引入
using System.Security.Permissions;
[PermissionSet(SecurityAction.Demand, Name = “FullTrust”)]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
webBrowser1.Url = new Uri(Path.Combine(Application.StartupPath, "marker.html"));
中含有path接口,需引入using System.IO;
3
我使用的是用odbc连接数据库,所以引用了using System.Data.Odbc;,也可以直接连接mysql,需要using引用,解决方案管理器里引用, OdbcConnection变为mysqlconnection, OdbcDataAdapter同理