上次和聯想的朋友交流了一下,提起是否可以在地圖上自由移動某個興趣點的表徵圖。以前還真沒考慮過這個問題,只記得Bing 地圖服務(Bing Maps)提供滑鼠事件的響應功能。於是專門找了總部的專家Chris Pendleton諮詢了一下,感謝CP很快就做了回覆。他以前寫過這樣的部落格,介紹如何在Bing 地圖服務上drag & drop pushpin。原文地址:http://www.bing.com/community/blogs/maps/archive/2008/10/28/draggable-pushpins-with-microsoft-virtual-earth.aspx。 如果以前看過我部落格的朋友,應該不難讀懂原始碼。此處我稍微做一下解釋。這個例子中增加了三個滑鼠事件: map.AttachEvent("onmousedown",MouseHandler); //滑鼠按下事件
map.AttachEvent("onmouseup",MouseHandler); //滑鼠按下後放開事件
map.AttachEvent("onmousemove",MouseHandler); //滑鼠移動事件然後,重載這三個滑鼠事件的具體實現方法:
function MouseHandler(e)
{
if (e.eventName == "onmousedown" && e.elementID != null) //滑鼠按下事件
{
dragShape = map.GetShapeByID(e.elementID); //獲得所點擊的對象
return true;
}else if (e.eventName == "onmouseup")
{
dragShape = null;
}else if (e.eventName == "onmousemove" && dragShape != null) //滑鼠移動事件
{
var x = e.mapX;
var y = e.mapY;
pixel = new VEPixel(x, y);
var LL = map.PixelToLatLong(pixel); //獲得滑鼠移動的位置
dragShape.SetPoints(LL); //將目標移動到滑鼠當前位置
return true; // prevent the default action
}
} 為了方便中國的使用者,我把原始碼中的地圖控制項URL改成Bing 地圖服務中國平台,這樣可以顯示直接中文地圖。完整原始碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">
<html>
<head>
<title>Drag and Drop</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- saved from url=(0014)about:internet -->
<script type="text/javascript" src="
http://dev.ditu.live.com/mapcontrol/mapcontrol.ashx?v=6.2"></script
>
<script type="text/javascript">
var map = null;
var dragShape = null;
function MouseHandler(e)
{
if (e.eventName == "onmousedown" && e.elementID != null)
{
dragShape = map.GetShapeByID(e.elementID);
return true;
}else if (e.eventName == "onmouseup")
{
dragShape = null;
}else if (e.eventName == "onmousemove" && dragShape != null)
{
var x = e.mapX;
var y = e.mapY;
pixel = new VEPixel(x, y);
var LL = map.PixelToLatLong(pixel);
dragShape.SetPoints(LL);
return true; // prevent the default action
}
}
function GetMap()
{
map = new VEMap('myMap');
map.LoadMap();
map.AttachEvent("onmousedown",MouseHandler);
map.AttachEvent("onmouseup",MouseHandler);
map.AttachEvent("onmousemove",MouseHandler);
var shape = new VEShape(VEShapeType.Pushpin, map.GetCenter());
shape.SetDescription("點擊滑鼠拖拽");
map.AddShape(shape);
var shape2 = new VEShape(VEShapeType.Pushpin, new VELatLong(39.616318, 116.331278));
shape2.SetDescription("我也可以移動的哦!");
map.AddShape(shape2);
}
</script>
</head>
<body onload="GetMap();">
<div id='myMap' style="position:relative; width:800px; height:600px;"></div>
<div id='resultDiv' style="position:relative; width:400px;">Drag the pushpins around on the map.</div>
</body>
</html>