import json import os from osgeo import osr from flask import request, jsonify from flask_restx import Resource, Namespace, reqparse, fields from app.defines import StatesCode ns = Namespace('conversion', description='坐标转换 API接口') coords_list = reqparse.RequestParser(bundle_errors=True) coords_list.add_argument('coords_list', type=str, required=True, location='form', help='点数组 [[x ,y], [x, y]]') @ns.route('/sh2000_to_wgs84') class Sh2000ToWgs84(Resource): @ns.doc(description='上海2000转wgs84') @ns.expect(coords_list) # @ns.marshal_with() def post(self): """上海2000转wgs84""" coords_list = request.form.get('coords_list') if coords_list: coords_list = json.loads(coords_list) else: return jsonify(code=StatesCode.PARA_ERROR, message='坐标点数组不能为空') try: wkt_path = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))), 'config', '上海2000.prj' ) with open(wkt_path, 'r') as f: wkt_str = f.read() srs_source = osr.SpatialReference() srs_source.ImportFromWkt(wkt_str) srs_dest = osr.SpatialReference() srs_dest.ImportFromEPSG(4326) transform = osr.CoordinateTransformation(srs_source, srs_dest) coords = transform.TransformPoints(coords_list) return jsonify(code=StatesCode.SUCCESS, message='成功', data=coords) except Exception as e: return jsonify(code=StatesCode.UNKNOWN_ERROR, message='失败', data=str(e)) @ns.route('/urban construction_to_wgs84') class UrbanConstruction(Resource): @ns.doc(description='城地转wgs84') @ns.expect(coords_list) def post(self): """城地转wgs84""" coords_list = request.form.get('coords_list') if coords_list: coords_list = json.loads(coords_list) else: return jsonify(code=StatesCode.PARA_ERROR, message='坐标点数组不能为空') try: wkt_path = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))), 'config', '城地转84.prj' ) with open(wkt_path, 'r') as f: wkt_str = f.read() srs_source = osr.SpatialReference() srs_source.ImportFromWkt(wkt_str) srs_dest = osr.SpatialReference() srs_dest.ImportFromEPSG(4326) transform = osr.CoordinateTransformation(srs_source, srs_dest) coords = transform.TransformPoints(coords_list) return jsonify(code=StatesCode.SUCCESS, message='成功', data=coords) except Exception as e: return jsonify(code=StatesCode.UNKNOWN_ERROR, message='失败', data=str(e))