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. }