image.png
xue.gif

一、封装画笔

  1. //如何是绘制正方方和矩形需要特殊处理
  2. /*
  3. @param{string}source 待添加的数据源
  4. @param{string} type 不同的类型(Point,LineString,Polygon,Circle,Square,Box)
  5. @param{function} callback 绘制完成调用
  6. */
  7. //draw.js
  8. function createDraw({source, type="Point", callback}) {
  9. let draw = null
  10. let geometryFunction = null
  11. let maxPoints = 0
  12. if (type == 'Square') {
  13. type = 'Circle'
  14. geometryFunction = ol.interaction.Draw.createRegularPolygon(4)
  15. } else if (type == 'Rectangle') {
  16. type = 'LineString'
  17. geometryFunction = function (coordinates, geometry) {
  18. if (!geometry) {
  19. //多边形
  20. geometry = new ol.geom.Polygon(null)
  21. }
  22. var start = coordinates[0]
  23. var end = coordinates[1]
  24. geometry.setCoordinates([
  25. [start,[start[0],end[1]],end,[end[0],start[1]],start]
  26. ])
  27. return geometry
  28. }
  29. maxPoints = 2
  30. }
  31. draw = new ol.interaction.Draw({
  32. source: source,
  33. type: type,
  34. geometryFunction: geometryFunction,
  35. maxPoints: maxPoints,
  36. })
  37. // callback && draw.on('drawend', callback)
  38. if (callback) {
  39. draw.on('drawend', callback)
  40. }
  41. return draw
  42. }

二、示例代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <script src="../../lib/include-openlayers-local.js"></script>
  9. <script src="../../js/Tian.js"></script>
  10. <script src="../../js/Draw.js"></script>
  11. </head>
  12. <body>
  13. <select id="select" onchange="handleChange(event)">
  14. <option value="None" selected="selected">无</option>
  15. <option value="Point">点</option>
  16. <option value="LineString">线</option>
  17. <option value="Polygon">多边形</option>
  18. <option value="Circle">圆</option>
  19. <option value="Square">正方形</option>
  20. <option value="Box">长方形</option>
  21. </select>
  22. <div id="map_container"></div>
  23. <script>
  24. const map = new ol.Map({
  25. target:"map_container",
  26. layers:[TianDiMap_vec,TianDiMap_cva],
  27. view:new ol.View({
  28. center:[114,30],
  29. projection:"EPSG:4326",
  30. zoom:4
  31. })
  32. })
  33. function handleChange(e){
  34. var type = e.target.value;
  35. }
  36. </script>
  37. </body>
  38. </html>