本文實例講述了WinForm調用百度地圖接口用法。分享給大家供大家參考,具體如下:
1、首先用一個html文件調用百度地圖接口(主要注冊一個序列號):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
<!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; } </style> <script type= "text/javascript" src= "http://api.map.baidu.com/api?v=1.5&ak=6c497f51c06477544e5fa6e9bd68f7c3" ></script> </head> <body> <div id= "allmap" > </div> </body> </html> <script type= "text/javascript" > //alert("Hello World"); var map = new BMap.Map( "allmap" ); // 創建Map實例 var point = new BMap.Point(121.504, 31.212); // 創建點坐標(經度,緯度) map.centerAndZoom(point, 11); // 初始化地圖,設置中心點坐標和地圖大小級別 map.addOverlay( new BMap.Marker(point)); // 給該坐標加一個紅點標記 //var traffic = new BMap.TrafficLayer(); // 創建交通流量圖層實例 //map.addTileLayer(traffic); // 將圖層添加到地圖上 map.addControl( new BMap.NavigationControl()); // 添加平移縮放控件 map.addControl( new BMap.ScaleControl()); // 添加比例尺控件 map.addControl( new BMap.OverviewMapControl()); //添加縮略地圖控件 map.addControl( new BMap.MapTypeControl()); //添加地圖類型控件 map.setCurrentCity( "上海" ); //設置地圖顯示的城市 map.enableScrollWheelZoom(); //啟用滾輪放大縮小 function setLocation(x,y){ //參數:經緯度 var point = new BMap.Point(x, y); map.centerAndZoom(point, 11); map.addOverlay( new BMap.Marker(point)); } </script> |
2、建立一個Winform項目,用一個WebBrower控件查看html文件、調用JavaScript代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace BaiDuMap { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load( object sender, EventArgs e) { try { //webBrowser1.Url = new Uri("https://www.baidu.com"); //這個文件于可執行文件放在同一目錄 webBrowser1.Url = new Uri(Path.Combine(Application.StartupPath, "GoogleMap.htm" )); } catch (Exception ex) { MessageBox.Show(ex.Message, "異常" , MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void webBrowser1_DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e) { //這里傳入x、y的值,調用JavaScript腳本 webBrowser1.Document.InvokeScript( "setLocation" , new object [] { 121.504, 39.212 }); } } } |
希望本文所述對大家C#程序設計有所幫助。