2019-05-23 Java根据地址计算日出日落时间(百度地图API)

获取百度地图API返回值(基于IP大致定位),并转化为JSON Object

import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/*
 * 基于IP大致定位
 * */

public class LocationByIP {
    public static JSONObject getJson(String ak) {
        LocationByIP locationByIP = new LocationByIP();
        String url = "http://api.map.baidu.com/location/ip?ak=" + ak + "&coor=bd09ll";
        //Console.log("请求:" + url);
        //get请求,获取响应实体
        String json = HttpRequest.get(url).execute().body();
        Console.log("响应内容:" + json);
        if (json != null && !"".equals(json)) {
            //JSONUtil.parseObj(jsonStr)会自动unicode编码转汉字
            return JSONUtil.parseObj(json);
        }
        return null;
    }
}

根据地址获取百度地图API返回值,并转化为JSON Object

import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;
public class EntCoordSyncJob {

    public static JSONObject getCoordinateJson(String dom, String ak, String sk) {
        if (dom != null && !"".equals(dom)) {
            dom = dom.replaceAll("\\s*", "").replace("#", "栋");
            try {
                //计算sn值
                String sn = getSn(dom, ak, sk);
                //对中文部分编码
                String key = java.net.URLEncoder.encode(dom, "UTF-8");
                String url = "http://api.map.baidu.com/geocoder/v2/?address=" + key + "&output=json&ak=" + ak + "&sn=" + sn;
                Console.log("请求:" + url);
                //get请求,获取响应实体
                String json = HttpRequest.get(url).execute().body();
                Console.log("响应内容:" + json);

                JSONObject obj = JSONUtil.parseObj(json);
                if (json != null && !"".equals(json) && "0".equals(obj.getStr("status"))) {
                    return obj;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getSn(String addressdom, String ak, String sk) throws UnsupportedEncodingException {
        Map paramsMap = new LinkedHashMap<String, String>();
        paramsMap.put("address", addressdom);
        paramsMap.put("output", "json");
        paramsMap.put("ak", ak);
        String paramsStr = toQueryString(paramsMap);
        String wholeStr = new String("/geocoder/v2/?" + paramsStr + sk);
        String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
        // 调用下面的MD5方法得到最后的sn签名
        return MD5(tempStr);
    }

    // 对Map内所有value作utf8编码,拼接返回结果
    public static String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey()).append("=");
            queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8")).append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    // 来自stackoverflow的MD5计算方法,调用了MessageDigest库函数,并把byte数组结果转换成16进制
    public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
        }
        return null;
    }
}

根据经纬度计算日出日落时间

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class SunTimesUtil {
    private static Double start = 0.0;
    private static Double end = 0.0;
    private static Double sRA = 0.0;
    private static Double sdec = 0.0;
    private static Double sr = 0.0;
    private static Double lon = 0.0;

    public static void main(String addressDom, String AK, String ipAK, String SK) {
        Calendar calendar = Calendar.getInstance();
        Console.log("当前时间:" + calendar.getTime());

        //获取经纬度坐标
        JSONObject jsonObject = EntCoordSyncJob.getCoordinateJson(addressDom, AK, SK);
        JSONObject jsonByIP = LocationByIP.getJson(ipAK);
        double lng = jsonObject.getJSONObject("result").getJSONObject("location").getDouble("lng");
        double lat = jsonObject.getJSONObject("result").getJSONObject("location").getDouble("lat");
        double x = 0.0, y = 0.0;
        String addr = "";
        if (jsonByIP != null && "0".equals(jsonByIP.getStr("status"))) {
            //point为当前城市中心点
            x = jsonByIP.getJSONObject("content").getJSONObject("point").getDouble("x");
            y = jsonByIP.getJSONObject("content").getJSONObject("point").getDouble("y");
            addr = jsonByIP.getJSONObject("content").getStr("address");
            Console.log("IP定位的经纬度:" + x + "," + y);
        } else {
            Console.log("IP定位出错");
        }

        //算出日出日落时间
        HashMap<String, Object> smap = getSunTimeAtDate(calendar.getTime(), lng, lat);
        //Console.log(smap);
        Console.log("地址:" + addressDom + "\n日出时间:" + smap.get("sunRise") + "\n日落时间:" + smap.get("sunSet"));

        HashMap<String, Object> ipmap = getSunTimeAtDate(calendar.getTime(), x, y);
        //Console.log(ipmap);
        Console.log("IP定位地址:" + addr + "\n日出时间:" + ipmap.get("sunRise") + "\n日落时间:" + ipmap.get("sunSet"));


    }

    public static HashMap<String, Object> getSunTimeAtDate(Date d, Double longitude, Double latitude) {
        long xcts = Days_since_2000_Jan_0(d);
        HashMap<String, Object> hm = new HashMap<>(2);
        try {
            hm = GetSunTime(xcts, longitude, latitude);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return hm;
    }


    public static HashMap<String, Object> GetSunTime(long day, Double longitude, Double latitude) throws ParseException {
        SunRiset(day, longitude, latitude, -35.0 / 60.0, 1, start, end);
        String sunrise = ToLocalTime(start);
        String sunset = ToLocalTime(end);
        HashMap<String, Object> hm = new HashMap<>(2);
        hm.put("sunRise", sunrise);
        hm.put("sunSet", sunset);
        return hm;
    }

    private static String ToLocalTime(Double utTime) {
        int hour = (int) (Math.floor(utTime));
        double temp = utTime - hour;
        hour += 8;
        temp = temp * 60;
        int minute = (int) (Math.floor(temp));
        String minuteStr = minute + " ";
        if (minute < 10) {
            minuteStr = "0" + minute;
        }
        return hour + ":" + minuteStr;
    }

    private static void Sunpos(Double d, Double lon, Double r) {
        /*
         * M 太阳的平均近点角,从太阳观察到的地球(=从地球看到太阳的)距近日点(近地点)的角度。
         * w 近日点的平均黄道经度。
         * e 地球椭圆公转轨道离心率。
         * E 太阳的偏近点角。计算公式见下面。
         * x, y 经纬度
         * v 真近点角,太阳在任意时刻的真实近点角。
         */
        Double M, w, e, E, x, y, v;

        //自变量的组成:2000.0时刻太阳黄经为356.0470度,此后每天约推进一度(360度/365天
        M = Revolution(356.0470 + 0.9856002585 * d);

        //近日点的平均黄经。
        w = 282.9404 + 4.70935E-5 * d;

        //地球公转椭圆轨道离心率的时间演化。以上公式和黄赤交角公式一样,不必深究。
        e = 0.016709 - 1.151E-9 * d;

        E = M + e * Radge * Sind(M) * (1.0 + e * Cosd(M));
        x = Cosd(E) - e;
        y = Math.sqrt(1.0 - e * e) * Sind(E);
        setSr(Math.sqrt(x * x + y * y));
        v = Atan2d(y, x);
        lon = v + w;
        setLon(lon);
        if (lon >= 360.0) {
            lon -= 360.0;
            setLon(lon);
        }
    }

    private static void Sun_RA_dec(Double d, Double RA, Double dec, Double r) {
        Double obl_ecl, x, y, z;
        Sunpos(d, lon, r);
        //计算太阳的黄道坐标。
        x = sr * Cosd(lon);
        y = sr * Sind(lon);
        //计算太阳的直角坐标。
        obl_ecl = 23.4393 - 3.563E-7 * d;
        //黄赤交角,同前。
        z = y * Sind(obl_ecl);
        y = y * Cosd(obl_ecl);
        //把太阳的黄道坐标转换成赤道坐标(暂改用直角坐标)。
        setsRA(Atan2d(y, x));
        setSdec(Atan2d(z, Math.sqrt(x * x + y * y)));
        //最后转成赤道坐标。显然太阳的位置是由黄道坐标方便地直接确定的,但必须转换到赤
        //道坐标里才能结合地球的自转确定我们需要的白昼长度。
    }

    private static int SunRiset(long day, Double longitude, Double lat, Double altit, int upper_limb, Double trise, Double tset) {
        /*
         * d,Days since 2000 Jan 0.0 (negative before)
         * sradius,太阳视半径,约16分(受日地距离、大气折射等诸多影响)
         * t,周日弧,太阳一天在天上走过的弧长。
         * tsouth,ime when Sun is at south
         * sidtime,当地恒星时,即地球的真实自转周期。比平均太阳日(日常时间)长3分56秒。
         */
        Double d, sradius, t, tsouth, sidtime;

        /* Return cde from function - usually 0 */
        int rc = 0;

        /* 计算观测地当日中午时刻对应2000.0起算的日数。 */
        d = day/* Days_since_2000_Jan_0(date)*/ + 0.5 - longitude / 360.0;

        /* 计算同时刻的当地恒星时(以角度为单位)。以格林尼治为基准,用经度差校正。 */
        sidtime = Revolution(GMST0(d) + 180.0 + longitude);

        /* 计算同时刻太阳赤经赤纬。 */
        Sun_RA_dec(d, sRA, sdec, sr);

        /* 计算太阳日的正午时刻,以世界时(格林尼治平太阳时)的小时计 */
        tsouth = 12.0 - Rev180(sidtime - sRA) / 15.0;

        /* 计算太阳视半径。0.2666是一天文单位处的太阳视半径(角度)*/
        sradius = 0.2666 / sr;

        /* 如果要用上边缘,就要扣除一个视半径。 */
        if (upper_limb != 0) {
            altit -= sradius;
        }

        //计算周日弧。直接利用球面三角公式。如果碰到极昼极夜问题,同前处理。
        Double cost;
        cost = (Sind(altit) - Sind(lat) * Sind(sdec)) /
                (Cosd(lat) * Cosd(sdec));
        if (cost >= 1.0) {
            rc = -1;
            t = 0.0;
        } else {
            if (cost <= -1.0) {
                rc = +1;
                t = 12.0;/* Sun always above altit */
            } else
                t = Acosd(cost) / 15.0;/* The diurnal arc, hours */
        }

        /* Store rise and set times - in hours UT */
        setStart(tsouth - t);
        setEnd(tsouth + t);
        return rc;
    }

    private static long Days_since_2000_Jan_0(Date date) {
        String d2000 = "2000-01-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long ll = 0L;
        try {
            ll = date.getTime() - sdf.parse(d2000).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ll / 1000 / 60 / 60 / 24;
    }

    private static Double Revolution(Double x) {
        return (x - 360.0 * Math.floor(x * Inv360));
    }

    private static Double Rev180(Double x) {
        return (x - 360.0 * Math.floor(x * Inv360 + 0.5));
    }

    private static Double GMST0(Double d) {
        Double sidtim0;
        sidtim0 = Revolution((180.0 + 356.0470 + 282.9404) +
                (0.9856002585 + 4.70935E-5) * d);
        return sidtim0;
    }

    private static Double Inv360 = 1.0 / 360.0;

    private static Double Sind(Double x) {
        return Math.sin(x * Degrad);
    }

    private static Double Cosd(Double x) {
        return Math.cos(x * Degrad);
    }

    private static Double Acosd(Double x) {
        return Radge * Math.acos(x);
    }

    private static Double Atan2d(Double y, Double x) {
        return Radge * Math.atan2(y, x);
    }

    private static Double Radge = 180.0 / Math.PI;
    private static Double Degrad = Math.PI / 180.0;

    public static Double getStart() {
        return start;
    }

    public static void setStart(Double start) {
        SunTimesUtil.start = start;
    }

    public static Double getsRA() {
        return sRA;
    }

    public static void setsRA(Double sRA) {
        SunTimesUtil.sRA = sRA;
    }

    public static Double getSdec() {
        return sdec;
    }

    public static void setSdec(Double sdec) {
        SunTimesUtil.sdec = sdec;
    }

    public static Double getSr() {
        return sr;
    }

    public static void setSr(Double sr) {
        SunTimesUtil.sr = sr;
    }

    public static Double getLon() {
        return lon;
    }

    public static void setLon(Double lon) {
        SunTimesUtil.lon = lon;
    }

    public static Double getEnd() {
        return end;
    }

    public static void setEnd(Double end) {
        SunTimesUtil.end = end;
    }

}

测试

package test;
import org.junit.jupiter.api.Test;
public class SunTimesTest {
    @Test
    public void test01() {
        String addressDom = "天津西青区中北科技产业园一区天软创业学院";
        String snAK = "********************************";
        String SK = "********************************";
        String ipAK = "********************************";/*浏览器端应用密钥*/

        SunTimesUtil.main(addressDom, snAK, ipAK, SK);

    }
}

测试结果

测试结果