这一篇,记录一下我调用的地图API实现的功能。下面介绍的都是一些片段的节选,不能直接复制就运行。在实现之前肯定要加载地图,先放一个webbroser控件,然后如下:
private void Form1_Load(object sender, EventArgs e)
{
string str_url = Application.StartupPath + "\\最终合并版本(昨晚修改).html";
Uri url = new Uri(str_url);
webBrowser1.Url = url;
webBrowser1.ObjectForScripting = this;
}
而为了能与JS交互,首先引入using System.Security.Permissions;,然后在namespace下必须加入两行:
namespace WebBroser_Test_V1._0
{
[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)
{
string str_url = Application.StartupPath + "\\最终合并版本(昨晚修改).html";
Uri url = new Uri(str_url);
webBrowser1.Url = url;
webBrowser1.ObjectForScripting = this;
// timer1.Enabled = true;
}
}
有了上面的基础,就可以实现以下功能了。
1.鼠标放在屏幕上移动时,实时的显示坐标。
放入一个timer和一个StatusScrip:
private void timer1_Tick(object sender, EventArgs e)
{
try
{
string tag_lng = webBrowser1.Document.GetElementById("mouselng").InnerText;
string tag_lat = webBrowser1.Document.GetElementById("mouselat").InnerText;
double dou_lng, dou_lat;
if (double.TryParse(tag_lng, out dou_lng) && double.TryParse(tag_lat, out dou_lat))
{
toolstatus_CurrentLocation.Text ="当前坐标:"+ dou_lng.ToString("F5") + "," + dou_lat.ToString("F5");
}
}
catch (Exception ee)
{ MessageBox.Show(ee.Message); }
}
放入一个button命名及代码如下:
private void btnGetLocation_Click(object sender, EventArgs e)
{
if (btnGetLocation.Text == "开启实时坐标")
{
timer1.Enabled = true;
btnGetLocation.Text = "关闭实时坐标";
}
else
{
btnGetLocation.Text = "开启实时坐标";
timer1.Enabled = false;
}
}
JS脚本如下:
var map =new BMap.Map("allmap");
var first_locate=new BMap.Point(108.953098,34.2778);
map.centerAndZoom(first_locate,15);
map.enableScrollWheelZoom(true);
map.addEventListener("mousemove",GetlngAndlat);
function GetlngAndlat(e)
{if(e.point.lng!=null)
{
document.getElementById("mouselng").innerHTML=e.point.lng;
document.getElementById("mouselat").innerHTML=e.point.lat;
}
}
2.开启测距工具(百度自己开发的)
拖一个按钮:
//开启测距工具按钮
private void btnOpenDistance_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("op