记一次百度和高德经纬度互转(不是你想的那样)

2018-09-15  本文已影响501人  生活简单些

首先,这里绝不是跟你讲如何百度和高德经纬度转换的算法。
其次,我在这里想抛下我的痛,不知道大家有没有遇到过App用的高德sdk,然而项目中服务端存储的各种资源信息中的经纬度却是百度的(其实也有部分是高德的),而且App和内嵌Web打交道,内嵌Web有的用百度有的用高德,由于特殊历史原因变得如此,而且未来也基本不能变过来,怎么办,只能继续。
在请求接口时候,传给接口的经纬度必须先转成百度的格式再发,获取到接口返回的经纬度必须先转成高德的再用,否则必定是BUG,可能你觉得没啥,但是现实中经常发现有人忘记转换导致了BUG,还有重复转换也导致了BUG,得非常非常细心才行,很累是不是?
于是,某天突然想到通过java注解来简化此工作,做到让经纬度自动转换成想要的格式:

// GD:高德, BD:百度
@LatLngInside(ConvertTo.GD)
private static class SearchParams {
    public String cityId;
    public String poiId;
    @Lat
    public double lat;
    @Lng
    public double lon;
    public String starIndex;
}

很显然以上注解的作用是将百度经纬度转成高德的。反之,想把高德转化成百度改成@LatLngInside(ConvertTo.BD)即可;
以JSON方式请求接口,在将请求对象转化成JSON之前先用LatLngConvertor转化一遍,以及获取接口返回值后生成的对象先通过LatLngConvertor转化一遍再抛给业务层处理。

经纬度变量单位都是double。所以,能实现自动经纬度转化必须保证经纬度是double类型,且加上对应注解。

public void doHttpRequest(Object reqBody){
    // 请求网络前先经纬度转换
    LatLngConvertor.autoConvertLatLng(reqBody);
    
    // 网络请求
    String resJson = doHttpRequest(reqBody);
    T response = decodeJSON(resJson);

    // 返回解析对象前先经纬度转换
    LatLngConvertor.autoConvertLatLng(response);

    handlerSuccess(response);
}

public void handlerSuccess(response){
// 业务代码处理
}

因此就写了一个遍历找经纬度并转换的工具:

public class LatLngConvertor {

    private static final double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    @NonNull
    public static LatLng gd2bd(@NonNull LatLng latLng) {
        double x = latLng.longitude, y = latLng.latitude;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lng = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        return new LatLng(bd_lat, bd_lng);
    }

    @NonNull
    public static LatLng gd2bd(@NonNull LatLonPoint latLonPoint) {
        double x = latLonPoint.getLongitude(), y = latLonPoint.getLatitude();
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lng = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        return new LatLng(bd_lat, bd_lng);
    }

    @NonNull
    public static LatLng bd2gd(double lat, double lng) {
        double x = lng - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        double gg_lng = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        return new LatLng(gg_lat, gg_lng);
    }

    // 转化入口
    public static void autoConvertLatLng(Object object){
        if (shouldIgnore(object)){
            return;
        }
        convertLatLng(object);
    }
    /**
     * 转化经纬度
     * @param object 必须为非基本数据类型
     */
    private static void convertLatLng(@Nullable Object object) {
        if (object == null) {
            return;
        }
        boolean present = object.getClass().isAnnotationPresent(LatLngInside.class);
        if (present) {
            try {
                findAndConvert(object);
                lookIntoFields(object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
           if(object instanceof List){
               List list = (List) object;
               for (Object item : list){
                   autoConvertLatLng(item);
               }
           } else {
               lookIntoFields(object);
           }
        }
    }

    private static void lookIntoFields(Object object){
        Field[] fields = object.getClass().getFields();
        for (Field field : fields) {
            int modifiers = field.getModifiers();
            if(Modifier.isPrivate(modifiers)
                    || Modifier.isFinal(modifiers)
                    || Modifier.isProtected(modifiers)
                    || Modifier.isStatic(modifiers)) {
                continue;
            }
            if (!field.isAccessible()){
                field.setAccessible(true);
            }
            try {
                Object value = field.get(object);
                if (!shouldIgnore(value)) {
                    convertLatLng(value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    // 经纬度的类型都是double,所以其他任何基本数据类型都忽略,包含String,同时不可能将字段放在map中所以LinkedTreeMap也忽略
    private static boolean shouldIgnore(Object object) {
        return object == null
                || object instanceof String
                || object instanceof Integer
                || object instanceof Float
                || object instanceof Long
                || object instanceof Short
                || object instanceof Byte
                || object instanceof Boolean
                || object instanceof LinkedTreeMap;
    }

    // 通过找到LatLngInside知道是高德转百度还是百度转高德
    private static void findAndConvert(Object object) throws IllegalAccessException {
        ConvertTo type = object.getClass().getAnnotation(LatLngInside.class).value();
        Field latField = null, lngField = null;
        Field[] fields = object.getClass().getFields();
        for (Field field : fields) {
            if (field.getType().isPrimitive()) {
                if (field.isAnnotationPresent(Lat.class)) {
                    if (field.getType() != double.class) {
                        throw new RuntimeException("class field with Lat annotation can only be double type -> " + field.getName());
                    }
                    latField = field;
                    doConvert(object, type, latField, lngField);
                } else if (field.isAnnotationPresent(Lng.class)) {
                    if (field.getType() != double.class) {
                        throw new RuntimeException("class field with Lng annotation can only be double type -> " + field.getName());
                    }
                    lngField = field;
                    doConvert(object, type, latField, lngField);
                }
            }
        }
    }

    // 只要找到对称的经度和纬度就可以转了
    private static void doConvert(Object object, ConvertTo convertTo, @Nullable Field latField, @Nullable Field lngField) throws IllegalAccessException {
        if (latField != null && lngField != null) {
            double lat = latField.getDouble(object);
            double lng = lngField.getDouble(object);
            if (lat == 0 || lng == 0) {
                return;
            }
            LatLng latLng = null;
            if (convertTo == ConvertTo.BD) {
                latLng = GeoUtils.gd2bd(new LatLng(lat, lng));
            } else if (convertTo == ConvertTo.GD) {
                latLng = GeoUtils.bd2gd(lat, lng);
            }
            if (latLng != null) {
                latField.setDouble(object, latLng.latitude);
                lngField.setDouble(object, latLng.longitude);
            }
        }
    }
}

首先, 遍历过程中一定要先过滤各种非double类型的字段,否则会遍历越陷越深,否则甚至会进入java.lang.Integer里尝试找经纬度,明显遍历过头了。其次,注意如果是List得把list item拿出来递归遍历查找经纬度。

上一篇 下一篇

猜你喜欢

热点阅读