본문 바로가기

파이썬(python)/FLASK

FLASK, 위 - 경도 계산 코드

#### FLASK를 활용한 거리계산 API 코드
# app.py
from flask import Flask, render_template, request, Response, redirect, url_for, session
import math
import numbers

app = Flask(__name__)

@app.route('/')
def dist1():
    return render_template('post.html')

'''
@app.route('/api/v1/geo/dist', methods = ['POST', 'GET'])
def dist2():
    if request.method == 'POST':
        result = request.form
        c = result
        return f'메롱 {c}'
'''

@app.route('/api/v1/geo/dist', methods = ['POST', 'GET'])
def dist2():
    """
    경위도 (x1, y1)과 (x2, y2)점의 거리를 반환
    Harversion Formula 이용하여 2개의 경위도간 거리를 구함 (단위:Km)
    """
    if request.method == 'POST':
        x1 = float(request.form["input1"])
        y1 = float(request.form["input2"])
        x2 = float(request.form["input3"])
        y2 = float(request.form["input4"])

        if x1 is None or y1 is None or x2 is None or y2 is None:
            return None
        assert isinstance(x1, numbers.Number) and (-180 <= x1 <= 180)
        assert isinstance(y1, numbers.Number) and (-90 <= y1 <= 90)
        assert isinstance(x2, numbers.Number) and (-180 <= x2 <= 180)
        assert isinstance(y2, numbers.Number) and (-90 <= y2 <= 90)

        R = 6371 # 지구의 반경(단위: km)

        dlon = (x2 - x1) * (math.pi / 180)
        dlat = (y2 - y1) * (math.pi / 180)

        a = math.sin(dlat / 2) * math.sin(dlat / 2) + (math.cos(y1*(math.pi / 180)) * math.cos(y2*(math.pi / 180)) * math.sin(dlon / 2) * math.sin(dlon /2))
        b = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
        c = round(R * b)

        return f'두 지점 사이의 거리는 {c}km 입니다.'


if __name__ == '__main__':
    app.run('0.0.0.0', port = 5010, threaded = True)

# post.html
<!DOCTYPE html>
<html>
<head>
        <meta charset="UTF-8">
        <title>HTML for python flask</title>
</head>

<body>
        <form action="http://ip주소/api/v1/geo/dist" method="POST">
                <p>위도:</p>
                <input type="text" name="input1" >
                <p>경도: </p>
                <input type="text" name="input2" >
                <p>위도2: </p>
                <input type="text" name="input3" >
                <p>경도2: </p>
                <input type="text" name="input4" >
                <p>위,경도를 입력하고 제출버튼을 누르세요.</p>
                <input type="submit">
        </form>
</body>