首先烟零,這里絕不是跟你講如何百度和高德經(jīng)緯度轉(zhuǎn)換的算法。
其次龙亲,我在這里想拋下我的痛浙值,不知道大家有沒有遇到過App用的高德sdk恳不,然而項目中服務端存儲的各種資源信息中的經(jīng)緯度卻是百度的(其實也有部分是高德的),而且App和內(nèi)嵌Web打交道亥鸠,內(nèi)嵌Web有的用百度有的用高德妆够,由于特殊歷史原因變得如此,而且未來也基本不能變過來负蚊,怎么辦神妹,只能繼續(xù)。
在請求接口時候家妆,傳給接口的經(jīng)緯度必須先轉(zhuǎn)成百度的格式再發(fā)鸵荠,獲取到接口返回的經(jīng)緯度必須先轉(zhuǎn)成高德的再用,否則必定是BUG伤极,可能你覺得沒啥蛹找,但是現(xiàn)實中經(jīng)常發(fā)現(xiàn)有人忘記轉(zhuǎn)換導致了BUG,還有重復轉(zhuǎn)換也導致了BUG哨坪,得非常非常細心才行庸疾,很累是不是?
于是当编,某天突然想到通過java注解來簡化此工作届慈,做到讓經(jīng)緯度自動轉(zhuǎn)換成想要的格式:
// 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;
}
很顯然以上注解的作用是將百度經(jīng)緯度轉(zhuǎn)成高德的忿偷。反之金顿,想把高德轉(zhuǎn)化成百度改成
@LatLngInside(ConvertTo.BD)
即可;
以JSON方式請求接口鲤桥,在將請求對象轉(zhuǎn)化成JSON之前先用LatLngConvertor轉(zhuǎn)化一遍揍拆,以及獲取接口返回值后生成的對象先通過LatLngConvertor轉(zhuǎn)化一遍再拋給業(yè)務層處理。
經(jīng)緯度變量單位都是double茶凳。所以嫂拴,能實現(xiàn)自動經(jīng)緯度轉(zhuǎn)化必須保證經(jīng)緯度是double類型,且加上對應注解慧妄。
public void doHttpRequest(Object reqBody){
// 請求網(wǎng)絡前先經(jīng)緯度轉(zhuǎn)換
LatLngConvertor.autoConvertLatLng(reqBody);
// 網(wǎng)絡請求
String resJson = doHttpRequest(reqBody);
T response = decodeJSON(resJson);
// 返回解析對象前先經(jīng)緯度轉(zhuǎn)換
LatLngConvertor.autoConvertLatLng(response);
handlerSuccess(response);
}
public void handlerSuccess(response){
// 業(yè)務代碼處理
}
因此就寫了一個遍歷找經(jīng)緯度并轉(zhuǎn)換的工具:
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);
}
// 轉(zhuǎn)化入口
public static void autoConvertLatLng(Object object){
if (shouldIgnore(object)){
return;
}
convertLatLng(object);
}
/**
* 轉(zhuǎn)化經(jīng)緯度
* @param object 必須為非基本數(shù)據(jù)類型
*/
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();
}
}
}
// 經(jīng)緯度的類型都是double顷牌,所以其他任何基本數(shù)據(jù)類型都忽略,包含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知道是高德轉(zhuǎn)百度還是百度轉(zhuǎn)高德
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);
}
}
}
}
// 只要找到對稱的經(jīng)度和緯度就可以轉(zhuǎn)了
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里嘗試找經(jīng)緯度运挫,明顯遍歷過頭了。其次套耕,注意如果是List得把list item拿出來遞歸遍歷查找經(jīng)緯度谁帕。