標籤:
之前需要做一個測量距離的工具,於是查了OpenLayers.Control.Measure,量算過程通過呼叫事件處理器 Handler 實現在 vector 圖層上的距離或面積的量算。
這裡做的是距離量算,點擊之後會彈出popup(OpenLayers.Popup),效果是點擊之後出現增加popup計算出之前幾個點之間的距離,並刪掉前面的popup(並沒有做出向百度那樣隨滑鼠移動變化距離的效果)。
調用方法MeasurePath();就可以查看效果啦
1 var measurePopup = null; 2 var messagelast = null; 3 4 //距離測量 5 var measureControl = new OpenLayers.Control.Measure(OpenLayers.Handler.Path, { 6 persist: true, 7 eventListeners: { 8 ‘measure‘: measureDistance, 9 ‘measurepartial‘: measurepartial10 }11 });12 13 14 function MeasurePath() {15 measureControl.updateHandler(OpenLayers.Handler.Path, { persist: true });16 map.addControl(measureControl);17 measureControl.activate();18 }19 function measureDistance(event) {20 messagelast = parseFloat(event.measure).toFixed(2) + "" + event.units;21 if (event.order > 1) {22 messagelast += "2";23 }24 //擷取滑鼠點擊處的經緯度25 var points = event.geometry.components;26 var point = points[points.length - 1];27 if (measurePopup != null)28 map.removePopup(measurePopup);29 measurePopup = new OpenLayers.Popup("chicken",30 //彈出框位置31 new OpenLayers.LonLat(point.x, point.y),32 //new OpenLayers.LonLat(position.x, position.y),33 null,34 messagelast,35 true,36 closeBoxCallback37 );38 measurePopup.autoSize = true;39 measurePopup.backgroundColor = "#06a09f";40 measurePopup.opacity = 0.8;41 map.addPopup(measurePopup);42 }43 44 function measurepartial(event) {45 var message = parseFloat(event.measure).toFixed(2) + "" + event.units;46 var points = event.geometry.components;47 var point = points[points.length - 1];48 if (measurePopup != null)49 map.removePopup(measurePopup);50 measurePopup = new OpenLayers.Popup("chicken",51 //彈出框位置52 new OpenLayers.LonLat(point.x, point.y),53 null,54 message,55 true,56 closeBoxCallback57 );58 measurePopup.autoSize = true;59 measurePopup.backgroundColor = "#06a09f";60 measurePopup.opacity = 0.8;61 if (points.length > 2)62 map.addPopup(measurePopup);63 }64 65 //function changeHandler(checked){ 66 // measureClick();67 // }68 69 function closeBoxCallback() {70 map.removePopup(measurePopup);71 measureControl.deactivate();72 map.removeControl(measureControl);73 messagelast = null;74 } View Code
popup有點醜,哈哈。雙擊結束一次測量,點擊popup的關閉按鈕(右上方的紅叉叉),結束測量事件。
popup隨滑鼠移動,OpenLayers.Control.Measure測量距離