transformation.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import json
  2. import os
  3. from osgeo import osr
  4. from flask import request, jsonify
  5. from flask_restx import Resource, Namespace, reqparse, fields
  6. from app.defines import StatesCode
  7. ns = Namespace('conversion', description='坐标转换 API接口')
  8. coords_list = reqparse.RequestParser(bundle_errors=True)
  9. coords_list.add_argument('coords_list', type=str, required=True, location='form', help='点数组 [[x ,y], [x, y]]')
  10. @ns.route('/sh2000_to_wgs84')
  11. class Sh2000ToWgs84(Resource):
  12. @ns.doc(description='上海2000转wgs84')
  13. @ns.expect(coords_list)
  14. # @ns.marshal_with()
  15. def post(self):
  16. """上海2000转wgs84"""
  17. coords_list = request.form.get('coords_list')
  18. if coords_list:
  19. coords_list = json.loads(coords_list)
  20. else:
  21. return jsonify(code=StatesCode.PARA_ERROR, message='坐标点数组不能为空')
  22. try:
  23. wkt_path = os.path.join(
  24. os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))),
  25. 'config', '上海2000.prj'
  26. )
  27. with open(wkt_path, 'r') as f:
  28. wkt_str = f.read()
  29. srs_source = osr.SpatialReference()
  30. srs_source.ImportFromWkt(wkt_str)
  31. srs_dest = osr.SpatialReference()
  32. srs_dest.ImportFromEPSG(4326)
  33. transform = osr.CoordinateTransformation(srs_source, srs_dest)
  34. coords = transform.TransformPoints(coords_list)
  35. return jsonify(code=StatesCode.SUCCESS, message='成功', data=coords)
  36. except Exception as e:
  37. return jsonify(code=StatesCode.UNKNOWN_ERROR, message='失败', data=str(e))
  38. @ns.route('/urban construction_to_wgs84')
  39. class UrbanConstruction(Resource):
  40. @ns.doc(description='城地转wgs84')
  41. @ns.expect(coords_list)
  42. def post(self):
  43. """城地转wgs84"""
  44. coords_list = request.form.get('coords_list')
  45. if coords_list:
  46. coords_list = json.loads(coords_list)
  47. else:
  48. return jsonify(code=StatesCode.PARA_ERROR, message='坐标点数组不能为空')
  49. try:
  50. wkt_path = os.path.join(
  51. os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))),
  52. 'config', '城地转84.prj'
  53. )
  54. with open(wkt_path, 'r') as f:
  55. wkt_str = f.read()
  56. srs_source = osr.SpatialReference()
  57. srs_source.ImportFromWkt(wkt_str)
  58. srs_dest = osr.SpatialReference()
  59. srs_dest.ImportFromEPSG(4326)
  60. transform = osr.CoordinateTransformation(srs_source, srs_dest)
  61. coords = transform.TransformPoints(coords_list)
  62. return jsonify(code=StatesCode.SUCCESS, message='成功', data=coords)
  63. except Exception as e:
  64. return jsonify(code=StatesCode.UNKNOWN_ERROR, message='失败', data=str(e))