C#程式設計學習(05):使用webbroswer控制元件顯示地圖並標註點位座標
阿新 • • 發佈:2018-12-19
控制元件準備:新建windows窗體應用程式,新增一個標記按鈕(btn_tagPos)、標籤控制元件(經度和緯度,實時經緯度顯示)、編輯框控制元件(記錄輸入的經度和緯度值)、webbroswer控制元件(webbroswer1)和計時器控制元件(timer1)
實現程式碼:
新增引用:
using System.Security.Permissions;
在專案的第一行新增程式碼:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")] [System.Runtime.InteropServices.ComVisibleAttribute(true)]
(1)在窗體載入時,顯示地圖到webbroswer控制元件中(IndexMap.html為百度地圖顯示的檔案)
private void Form5_Load_1(object sender, EventArgs e) { Uri url = new Uri(Application.StartupPath + "\\IndexMap.html"); webBrowser1.Url = url; webBrowser1.ObjectForScripting = this; //webBrowser1.ScriptErrorsSuppressed = true; timer1.Enabled = true; }
(2)在計時器中新增程式碼,用於顯示實時座標
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)) { this.lab_lb.Text = "當前座標:" + dou_lng.ToString("F5") + "," + dou_lat.ToString("F5"); } } catch (Exception ee) { //MessageBox.Show(ee.Message); } }
(3)輸入座標顯示經緯度
private void btn_tagpos_Click_1(object sender, EventArgs e)
{
if(txb_jingdu == null || txb_weidu == null)
{
MessageBox.Show("請檢查是否填入了經緯度座標!", "座標錯誤提示");
return;
}
//"116.399", " 39.910"
object[] args = { txb_jingdu.Text, txb_weidu.Text};
webBrowser1.Document.InvokeScript("addMarker", args);
}
對應html檔案的JScript程式碼,首先清除已有標記,然後在新增新的標記:
function addMarker(x, y) {
map.clearOverlays(); //清除地圖中已有的標記
var point = new BMap.Point(x, y);
var marker = new BMap.Marker(point); // 建立標註
map.addOverlay(marker); //用於新增標記
map.centerAndZoom(point, 11); //用於將地圖縮放至輸入的座標點
}
拓展程式碼:deletePoint函式,先呼叫getOverlays()函式用於得到所有覆蓋物資訊;再呼叫的removeOverlay()函式是一次移除一個指定覆蓋物
function deletePoint(){
var allOverlay = map.getOverlays();
for (var i = 0; i < allOverlay.length -1; i++){
if(allOverlay[i].getLabel().content == "我是id=1"){
map.removeOverlay(allOverlay[i]);
return false;
}
}
}
附件:用到的IndexMap.html檔案
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello Map</title>
<script type="text/javascript"src="http://api.map.baidu.com/api?key=59db371659c04947a1ff044e80565718&v=1.4&services=true">
</script>
<!--載入滑鼠測距工具-->
<script src="DistanceTool_min.js" type="text/javascript"></script>
<!--載入滑鼠繪製工具-->
<script type="text/javascript" src="DrawingManager_min.js"></script>
<link rel="stylesheet" href="DrawingManager_min.css" />
</head>
<body>
<div id="mouselng" style="visibility:hidden"></div>
<div id="mouselat" style="visibility:hidden"></div>
<div style="width:1000px;height:600px;border:1px solid gray" id="container">
</div>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("container");
map.centerAndZoom(new BMap.Point(108.876433, 36.269395), 5);
map.addControl(new BMap.ScaleControl()); //新增比例尺控制元件(左下角顯示的比例尺控制元件)
map.addControl(new BMap.OverviewMapControl());// 縮圖控制元件
var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE });
map.addControl(ctrl_nav);//新增標準地圖控制元件(左上角的放大縮小左右拖拽控制元件)
map.enableDragging(); //啟用地圖拖拽事件,預設啟用(可不寫)
map.enableScrollWheelZoom(); //啟用地圖滾輪放大縮小
map.enableDoubleClickZoom(); //啟用滑鼠雙擊放大,預設啟用(可不寫)
map.enableKeyboard(); //啟用鍵盤上下左右鍵移動地圖
map.enableContinuousZoom(); // 開啟連續縮放效果
map.enableInertialDragging(); // 開啟慣性拖拽效果
//實時顯示地圖座標 strat
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;
}
}
//實時顯示地圖座標 end
//測量距離 strat
function openGetDistance() {
var myDis=new BMapLib.DistanceTool(map);//map為上面已經初始化好的地圖例項
myDis.open();
}
//測量距離 end
//左右擊滑鼠給地圖上放marker strat 放標註,並且將JS的資料傳送給WINFORM
function PUTANDSEND() {
//右鍵標記
map.addEventListener("rightclick", putAndsend);
//左鍵標記
//map.addEventListener("click", putAndsend);
}
var marker_num = 0;
function putAndsend(e)
{
//放標註
var p1=new BMap.Point(e.point.lng,e.point.lat);
var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24));
var marker = new BMap.Marker(p1, { icon: myIcon }); // 建立標註
map.addOverlay(marker); // 將標註新增到地圖中
marker_num++;//標註索引,這個是個全域性變數
var whichCar=window.external.setWhichCar();
var label=new BMap.Label(whichCar+"號車-座標"+marker_num+":"+
"("+e.point.lng+","+e.point.lat+")",{offset:new BMap.Size(20,-10)});
marker.setLabel(label);
//給WINFORM傳值
window.external.PutIntotextBox(marker_num,whichCar,e.point.lng,e.point.lat);
}
//左右擊滑鼠給地圖上放marker end
//在地圖上畫軌跡 strat
function DrawOrit1()
{
var Array=[];
var total_num= window.external.getRowsNumber();
for(var i=0;i<=2*total_num-1;i++)
{
Array.push(window.external.Getpoints(i));
}
var PointArr=[];
for(var i=0;i<=Array.length-1;i+=2)
{//偶數索引存經度,奇數存維度
PointArr.push(new BMap.Point(Array[i],Array[i+1]));
}
var polyline = new BMap.Polyline(PointArr, {strokeColor:"blue", strokeWeight:6, strokeOpacity:0.5}); //定義折線
map.addOverlay(polyline);
window.external.ClearRows_num();//重置窗體計數器
}
//在地圖上畫軌跡 end
//在地圖上畫圓形或者方形 strat
// 編寫自定義函式,建立標註
function addMarker(point) {
var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24));
var marker = new BMap.Marker(point, { icon: myIcon }); // 建立標註
map.addOverlay(marker); // 將標註新增到地圖中
}
function addMarker(x, y) {
map.clearOverlays();
var point = new BMap.Point(x, y);
var marker = new BMap.Marker(point); // 建立標註
map.addOverlay(marker);
map.centerAndZoom(point, 11);
}
var overlays = [];
var complete=function(e)
{
overlays.push(e.overlay);
if (e.drawingMode == BMAP_DRAWING_CIRCLE)
{
//隨便賦值,重新整理一遍資料庫(此方法只為演示,實際中要另考慮演算法)
var test= window.external.SearchAllCars(0);
var circle_radius=e.overlay.getRadius();//半徑
//圓心
var circle_point=new BMap.Point(e.overlay.getCenter().lng,e.overlay.getCenter().lat);
//從WINFORM裡取出資料
var dangerCars=[];
var pointlen=window.external.GetdangerNum();
for(var k=0;k<=pointlen-1;k++)
{
dangerCars.push(window.external.SearchAllCars(k));
}
var BMappoints=[];//建立百度地圖介面規定的陣列
for(var j=0;j<=dangerCars.length-1;j+=2)
{
BMappoints.push(new BMap.Point(dangerCars[j],dangerCars[j+1]));
}
for(var i=0;i<=BMappoints.length-1;i++)
{
if(map.getDistance(circle_point,BMappoints[i])<=circle_radius)
{
//AddMarker(BMappoints[i]);//呼叫新增標註版本V3.0
var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24));
var marker1 = new BMap.Marker(BMappoints[i], { icon: myIcon }); // 建立標註
map.addOverlay(marker1); // 將標註新增到地圖中
}
}
}
};
//線條樣式
var styleOptions = {
strokeColor:"blue", //邊線顏色。
fillColor:"blue", //填充顏色。當引數為空時,圓形將沒有填充效果。
strokeWeight: 3, //邊線的寬度,以畫素為單位。
strokeOpacity: 1, //邊線透明度,取值範圍0 - 1。
fillOpacity: 0.3, //填充的透明度,取值範圍0 - 1。
strokeStyle: 'solid' //邊線的樣式,solid或dashed。
}
//例項化滑鼠繪製工具
var drawingManager = new BMapLib.DrawingManager(map, {
isOpen: true, //是否開啟繪製模式
enableDrawingTool: true, //是否顯示工具欄
drawingToolOptions: {
anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
offset: new BMap.Size(5, 5), //偏離值
scale: 0.8, //工具欄縮放比例
drawingTypes : [
BMAP_DRAWING_CIRCLE,
BMAP_DRAWING_RECTANGLE
]
},
circleOptions: styleOptions, //圓的樣式
rectangleOptions: styleOptions //矩形的樣式
});
//新增滑鼠繪製工具監聽事件,用於獲取繪製結果
drawingManager.addEventListener('overlaycomplete', complete);
//回撥獲得覆蓋物資訊,未使用該版本
var overlaycomplete = function (e) {
overlays.push(e.overlay);
var result = "";
result += e.drawingMode + ":";
if (e.drawingMode == BMAP_DRAWING_CIRCLE) {
var circle_radius = e.overlay.getRadius();
var circle_point = new BMap.Point(e.overlay.getCenter().lng, e.overlay.getCenter().lat);
alert(map.getDistance(circle_point, tests[1]));
for (var i = 0; i < 3; i++) {
if (map.getDistance(circle_point, tests[i]) <= circle_radius) {
//AddMarker(tests[i]);
var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24));
var marker1 = new BMap.Marker(tests[i], { icon: myIcon }); // 建立標註
map.addOverlay(marker1); // 將標註新增到地圖中
}
}
alert(result);
}
if (e.drawingMode == BMAP_DRAWING_POLYLINE || e.drawingMode == BMAP_DRAWING_POLYGON || e.drawingMode == BMAP_DRAWING_RECTANGLE) {
result += ' 所畫的點個數:' + e.overlay.getPath()[1].lng;
alert(result);
}
};
//drawingManager.enableCalculate();
//----------------------公用方法,用元素id獲取元素的值-------------------
function $(id){
return document.getElementById(id);
}
//------------------畫矩形,讓WINFORM呼叫---------------
function drawRec(){
drawingManager.setDrawingMode(BMAP_DRAWING_RECTANGLE);}
//------------------畫圓,讓WINFORM呼叫----------------
function drawCircle(){
drawingManager.setDrawingMode(BMAP_DRAWING_CIRCLE);}
//------------------清除所有已畫圖形,讓WINFORM呼叫--------------------
function clearAll() {
for(var i = 0; i < overlays.length; i++){
map.removeOverlay(overlays[i]);
}
overlays.length = 0
}
//在地圖上畫圓形或者方形 end
</script>