由於我的業務需求是可以在底圖上進行一些操作,比如繪制電子圍欄等功能,於是需要使用openlayers中的畫筆功能,接下來開始一波操作
還是上一篇的html頁面, 直接上代碼
<!doctype html> <html lang="en"> <head> <script src="./js/ol.js"></script> <link rel="stylesheet" href="./js/ol.css" type="text/css"> <style> .map { height: 80vh; width: 100%; border: 1px solid red; } </style> <title>OpenLayers example</title> </head> <body> <h2>My Map</h2> <label>Geometry type </label> <select id="type"> <option value="Point">Point</option> <option value="LineString">LineString</option> <option value="Polygon">Polygon</option> <option value="Circle">Circle</option> <option value="None">None</option> </select> <div id="map" class="map"></div> <script type="text/javascript"> //地圖設置中心,設置到成都,在本地離線地圖offlineMapTiles剛好有一張zoom為4的成都瓦片 var center = ol.proj.transform([104.06667, 30.66667], 'EPSG:4326', 'EPSG:3857'); //計算靜態地圖映射到地圖上的范圍,圖片像素為550*344,保持比例的情況下,把分辨率放大一些 var extent = [ center[0] - 2718 * 1000 / 2, center[1] - 2327 * 1000 / 2, center[0] + 2718 * 1000 / 2, center[1] + 2327 * 1000 / 2 ]; var map = new ol.Map({ target: 'map', view: new ol.View({ center: center, zoom: 8, minZoom: 5, maxZoom: 12 }) }); //加載靜態圖層 map.addLayer(new ol.layer.Image({ source: new ol.source.ImageStatic({ url: './images/logo2.png', // 靜態地圖 imageExtent: extent //映射到地圖的范圍 }) })); // 添加一個繪制的線使用的layer var drawLayer = new ol.layer.Vector({ //layer所對應的source source: new ol.source.Vector(), }) //把layer加入到地圖中 map.addLayer(drawLayer); //先看看選中的畫什么,點?線?面?。。 var typeSelect = document.getElementById('type'); var draw; // 在這兒定義一個全局的繪制變量,方便一會去除它 function addInteraction() { var value = typeSelect.value; if (value !== 'None') { draw = new ol.interaction.Draw({ source: drawLayer.getSource(), type: typeSelect.value }); map.addInteraction(draw); } } /** * 處理選中不同的繪制方式的方法,通過監聽typeSelect值的變化 */ typeSelect.onchange = function () { //先移除上一個Interaction map.removeInteraction(draw); //再根據typeSelect的值繪制新的Interaction addInteraction(); }; addInteraction(); </script> </body> </html>
然后你會看到如下的界面
鼠標hover進去以后會默認有一個點

說明一下,初始化的圖片和上一篇博客的里的圖片相比較放大了,是因為圖片的寬度別我調了,沒有影響的,你們調回正常也是可以的,還有一種可能就是我放大了底圖導致的,都是沒有影響的
然后你可以先選擇上面的下拉框的內容,然后再地圖上進行繪制,效果是:
線:

圓:

polygon:

其余的你們可以自己去試試
