package com.fs.watch.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class GeocodingUtils {
    private static final MyHttpUtils httpUtils = new MyHttpUtils();
    private static final String API_KEY = "c52e38a111a39d507591958b4ba86bbe";  // 替换为你的高德地图API密钥
    private static final String GEOCODE_API_URL = "https://restapi.amap.com/v3/geocode/regeo";

    /**
     * 通过经纬度获取详细地址
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @return 返回获取的地址信息，如果请求失败返回null
     */
    public static String getAddressFromLatLng(double latitude, double longitude) {
        String address = null;
        HashMap<String, Object> param = new HashMap<>();
        param.put("key", API_KEY);
        param.put("location", latitude + "," + longitude);
        Map response = httpUtils.getRequest("restapi.amap.com", "/v3/geocode/regeo", param);
        // 检查返回的 status 是否为 "1"
        if ("1".equals(response.get("status"))) {
            Map<String,String>  regeocode= JSONObject.parseObject(response.get("regeocode").toString(),HashMap.class);
            if (regeocode != null) {
                // 检查 formatted_address 是否是字符串或数组
                String formattedAddressObj = regeocode.get("formatted_address");
                if (formattedAddressObj != null) {
                    address = formattedAddressObj;
                }
            } else {
                System.err.println("Regeocode not found in the response");
            }
        } else {
            System.err.println("API returned error. Status: " + response.get("status"));
        }
        return address;
    }
}
