package com.sckw.core.utils;

import java.net.URL;
import java.util.StringJoiner;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class LocUtils {

    public static String getAddressName(String point) {
        // 返回数据
        String res = "";
        if (point == null || point.equals("0.0,0.0")) {
            return res;
        }
        // 请求头
        String urlHead = "http://restapi.amap.com/v3/geocode/regeo?key=8325164e247e15eea68b59e89200988b&s=rsv3&location=";
        // 请求参数
        String urlParam = "&radius=2800&callback=jsonp_452865_&platform=JS&logversion=2.0&sdkversion=1.3&appname=http%3A%2F%2Flbs.amap.com%2Fconsole%2Fshow%2Fpicker&csid=49851531-2AE3-4A3B-A8C8-675A69BCA316";
        StringJoiner sj = new StringJoiner("");
        // 完整请求地址
        String requestUrl = sj.add(urlHead).add(point).add(urlParam).toString();

        String methodStr = "GET";
        String codeType = "UTF-8";
        try {
            URL url = new URL(requestUrl);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod(methodStr);
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(), codeType));
            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
            in.close();

            if (!"".equalsIgnoreCase(res)) {
                String regeoKey = "regeocode";
                String addressKey = "formatted_address";
                String strAddrs = res.substring(res.indexOf("(") + 1, res.lastIndexOf(")"));
                JSONObject addJson = JSON.parseObject(strAddrs);
                JSONObject regeocodeObject = (null != addJson ? addJson.getJSONObject(regeoKey) : null);
                res = (null != regeocodeObject ? regeocodeObject.getString(addressKey) : "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return res;
        }
        return res;
    }

    public static void main(String[] args) {
        String res = getAddressName("118.879289,38.052237");
        System.out.println(res);
    }
}
