import io
import requests
import math
import numpy as np
import json	
import folium

from bs4 import BeautifulSoup
from pyproj import Transformer

#위도(latitude), 경도(longitude) 
Earth_r = 20037508.34 # meter

def GetJusofromGPS(lat,lon):
    ret_juso = ["", "", "", ""]

    if lat <= 0.0 or lon <= 0.0:
        return ret_juso

    apiurl = "https://api.vworld.kr/req/address?"	
    params = {	
    	"service": "address",	
    	"request": "getaddress",	
    	"crs": "epsg:4326",	
    	"point": f"{lon},{lat}",	
    	"format": "json",	
    	"type": "BOTH",	
    	"key": "7E59C6EC-6BB0-3ED9-ACCC-4158869D7CFD"	
    }
    
    response = requests.get(apiurl, params=params)	
    
    data = None
    if response.status_code == 200:	
        data = response.json()

        print(data)
        
        if "OK" == data["response"]["status"]:
            for item in data["response"]["result"]:
                type = item["type"]

                if type.lower() == "parcel":
                    ret_juso[0] = item["text"]
                    ret_juso[1] = item["structure"]["level4L"]
                elif type.lower() == "road":
                    ret_juso[2] = item["text"] 
                    ret_juso[3] = item["structure"]["level4L"]

        else:
            print( f"{data["response"]["status"] } : {data["error"]["code"] }" )
        
    return ret_juso

# VWorld 좌표계  : EPSG:3857
# GPS 좌표계  : EPSG:4326
# 경도는 람다 (\lambda)  위도는 파이 (\phi)  
def Transform4326to3857(srcLat, srcLon):
    transformer = Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)

    # 좌표 변환 실행
    x, y = transformer.transform(srcLon, srcLat)

    return y, x




#37.536514,126.977138
#37.541047,126.990966
#37.539324791666665,126.98787990833334
#37.539325,126.987880      
#GetJusofromGPS(37.52356569972222,126.9683578) 
#"14105383.450839", "3950184.1545913"
#37.36340831688752, 35.48510801650072
#"3950184.1545913", "14105383.450839"

