想說乾脆多研究一點GoogleMap關於畫圖的功能好了。
DrawingManager
1、使用到的庫:drawing
<script src=”https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=drawing“></script>
2、創建方法:
1 2 3 4 5 6 7 8 9 10 11 |
var drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: null, drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, drawingModes: [ google.maps.drawing.OverlayType.POLYGON, google.maps.drawing.OverlayType.RECTANGLE ] } }); |
3、通過設定position來將DrawingManager顯示在某一個位置,比如TOP_CENTER.
位置請參考:
其中T = Top, C = Center R = Right ,B = Bottom
所以TL = TOP_LEFT , RC = RIGHT_CENTER, BR = BOTTOM_RIGHT……
比如上圖就是將Drawing Tool Box放在了TOP_CENTER的位置。
4、只有畫是不夠的,我需要一個清除按鈕。
下面的代碼來自stackoverflow的一個例子,不過已經找不到來源了,例子中建立了一個div然後push進去。
1 2 3 |
var clearControlDiv = document.createElement('div'); setupClearControl(clearControlDiv, map); map.controls[google.maps.ControlPosition.TOP_CENTER].push(clearControlDiv); |
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 |
function setupClearControl(controlDiv, map) { // 給清除按鈕的背景設定樣式. var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#ffff99'; controlUI.style.borderStyle = 'solid'; controlUI.style.borderWidth = '1px'; controlUI.style.borderColor = '#ccc'; controlUI.style.height = '23px'; controlUI.style.marginTop = '5px'; controlUI.style.marginLeft = '-6px'; controlUI.style.paddingTop = '0px'; controlUI.style.cursor = 'pointer'; controlUI.style.textAlign = 'center'; // 這個title是滑鼠指上去的時候,會顯示的tag controlUI.title = '清除畫過的農地'; controlDiv.appendChild(controlUI); // 給清除按鈕中的文字div設定樣式. var controlText = document.createElement('div'); controlText.style.fontFamily = '黑體'; controlText.style.fontSize = '16px'; controlText.style.paddingLeft = '4px'; controlText.style.paddingRight = '4px'; controlText.style.marginTop = '0px'; controlText.innerHTML = '清除全部'; controlUI.appendChild(controlText); // 給按鈕添加事件 google.maps.event.addDomListener(controlUI, 'click', function () { clearMyFarm(); }); } |