本文首发在我的个人博客: http://www.geekqian.com/post/c28e2c34.html

转载请注明出处

参考资料:

  1. http://blog.csdn.net/jc_0203/article/details/51143770
  2. http://blog.csdn.net/u010919133/article/details/72399618
  3. https://github.com/taoweiji/JZLocationConverter-for-Android/blob/master/JZLocationConverter.java
  4. https://www.cnblogs.com/lihualuo/p/3527495.html
  5. http://blog.csdn.net/u010331406/article/details/51484330

时间紧迫直接开撸.

首先在需要定位的地方先申请权限. 这一步略过不谈, 清单文件

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

然后直接调用下面代码.

注意! 百度在线解析有日限额, 貌似未认证的用户是6千次吧好像. 账户认证了开发者信息后就可以免费提额到30万每天.

—–更新—–

其中 ak 是百度地图平台的应用 key, http://lbsyun.baidu.com/apiconsole/key 到这个地址去登录并创建应用, 注意应用的创建需要有 SHA1 值, 获取 SHA 值的方式: 到 JDK 安装目录下的 bin 目录中 使用命令: keytool -list -v -keystore 绝对路径/keystore名称 然后输入 keystore 密码后就会显示在控制台了. 选中并回车即可复制.

应用创建成功后会有一个 ak 显示出来, 至于 mCode嘛, 其实也是属于这个创建的应用的安全码, 创建了应用后点击设置会跳转到一个新的页面, 里面就有安全码显示.

—–更新——-

LocationManager manager = (LocationManager) MyApplication.getContext().getSystemService(Context.LOCATION_SERVICE);//获得位置服务

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度,如果设置为高精度,依然获取不了location。
criteria.setAltitudeRequired(false);//不要求海拔
criteria.setBearingRequired(false);//不要求方位
criteria.setCostAllowed(true);//允许有花费
criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
//从可用的位置提供器中,匹配以上标准的最佳提供器
String provider = manager.getBestProvider(criteria, true);
if (provider == null) return "";

// 判断是否有权限,  ACCESS_FINE_LOCATION 获取精确位置   ACCESS_COARSE_LOCATION 获取错略位置
if (ActivityCompat.checkSelfPermission(MyApplication.getContext(),
        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
        ActivityCompat.checkSelfPermission(MyApplication.getContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    return "";
}

Location location = manager.getLastKnownLocation(provider);
if (location != null) {
    getLocationFormBaiDu(location);//得到当前经纬度并开启线程去反向地理编码
}

    /** 调用百度在线API获取详细位置
     * @param location 位置
     */
    private static void getLocationFormBaiDu(Location location) {
    double lng = location.getLongitude();
    double lat = location.getLatitude();
    // 用location获取到的坐标是地球坐标,要把地球坐标转换为百度坐标
    JZLocationConverter.LatLng latLng = JZLocationConverter.wgs84ToBd09(new JZLocationConverter.LatLng(lat, lng));
    String longitude = latLng.longitude +"";
    String latitude = latLng.latitude + "";

    String ak = Config.BAI_DU_AK;
    String mCode = Config.MCODE;
    String url = "http://api.map.baidu.com/geocoder/v2/?location="
            + latitude + "," + longitude + "&output=json&pois=1&ak=" + ak + "&mcode=" + mCode;
    OkHttpUtils.get().url(url).build().execute(new StringCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {

        }

        @Override
        public void onResponse(String response, int id) {
            try {
                Gson gson = new Gson();
                BaiDuLocationBean locationBean = gson.fromJson(response, BaiDuLocationBean.class);
                if (locationBean != null) {
                    BaiDuLocationBean.ResultBean result = locationBean.getResult();
                    String address = result.getFormatted_address();
                    sLocation = address;
                    LogUtils.print("address == " + address);
                    // 把地址保存到sp
                    SPUtils.putString(Config.LOCATION , address);
                }
            } catch (Exception e) {
                LogUtils.print("百度地址解析失败 >>>>>" + response);
            }
        }
    });
}

/** 坐标转换帮助类
 * Created by taoweiji on 15/3/26.
 */
public class JZLocationConverter {

private static final double LAT_OFFSET_0(double x, double y) {
    return -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
}

private static final double LAT_OFFSET_1(double x, double y) {
    return (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
}

private static final double LAT_OFFSET_2(double x, double y) {
    return (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
}

private static final double LAT_OFFSET_3(double x, double y) {
    return (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
}

private static final double LON_OFFSET_0(double x, double y) {
    return 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
}

private static final double LON_OFFSET_1(double x, double y) {
    return (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
}

private static final double LON_OFFSET_2(double x, double y) {
    return (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
}

private static final double LON_OFFSET_3(double x, double y) {
    return (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;
}

private static double RANGE_LON_MAX = 137.8347;
private static double RANGE_LON_MIN = 72.004;
private static double RANGE_LAT_MAX = 55.8271;
private static double RANGE_LAT_MIN = 0.8293;

private static double jzA  = 6378245.0;
private static double jzEE = 0.00669342162296594323;

public static double transformLat(double x, double y) {
    double ret = LAT_OFFSET_0(x, y);
    ret += LAT_OFFSET_1(x, y);
    ret += LAT_OFFSET_2(x, y);
    ret += LAT_OFFSET_3(x, y);
    return ret;
}

public static double transformLon(double x, double y) {
    double ret = LON_OFFSET_0(x, y);
    ret += LON_OFFSET_1(x, y);
    ret += LON_OFFSET_2(x, y);
    ret += LON_OFFSET_3(x, y);
    return ret;
}

public static boolean outOfChina(double lat, double lon) {
    if (lon < RANGE_LON_MIN || lon > RANGE_LON_MAX)
        return true;
    if (lat < RANGE_LAT_MIN || lat > RANGE_LAT_MAX)
        return true;
    return false;
}

public static LatLng gcj02Encrypt(double ggLat, double ggLon) {
    LatLng resPoint = new LatLng();
    double mgLat;
    double mgLon;
    if (outOfChina(ggLat, ggLon)) {
        resPoint.latitude = ggLat;
        resPoint.longitude = ggLon;
        return resPoint;
    }
    double dLat = transformLat(ggLon - 105.0, ggLat - 35.0);
    double dLon = transformLon(ggLon - 105.0, ggLat - 35.0);
    double radLat = ggLat / 180.0 * Math.PI;
    double magic = Math.sin(radLat);
    magic = 1 - jzEE * magic * magic;
    double sqrtMagic = Math.sqrt(magic);
    dLat = (dLat * 180.0) / ((jzA * (1 - jzEE)) / (magic * sqrtMagic) * Math.PI);
    dLon = (dLon * 180.0) / (jzA / sqrtMagic * Math.cos(radLat) * Math.PI);
    mgLat = ggLat + dLat;
    mgLon = ggLon + dLon;

    resPoint.latitude = mgLat;
    resPoint.longitude = mgLon;
    return resPoint;
}

public static LatLng gcj02Decrypt(double gjLat, double gjLon) {
    LatLng gPt = gcj02Encrypt(gjLat, gjLon);
    double dLon = gPt.longitude - gjLon;
    double dLat = gPt.latitude - gjLat;
    LatLng pt = new LatLng();
    pt.latitude = gjLat - dLat;
    pt.longitude = gjLon - dLon;
    return pt;
}

public static LatLng bd09Decrypt(double bdLat, double bdLon) {
    LatLng gcjPt = new LatLng();
    double x = bdLon - 0.0065, y = bdLat - 0.006;
    double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
    double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
    gcjPt.longitude = z * Math.cos(theta);
    gcjPt.latitude = z * Math.sin(theta);
    return gcjPt;
}

public static LatLng bd09Encrypt(double ggLat, double ggLon) {
    LatLng bdPt = new LatLng();
    double x = ggLon, y = ggLat;
    double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
    double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
    bdPt.longitude = z * Math.cos(theta) + 0.0065;
    bdPt.latitude = z * Math.sin(theta) + 0.006;
    return bdPt;
}

/**
 * @param location 世界标准地理坐标(WGS-84)
 * @return 中国国测局地理坐标(GCJ-02)<火星坐标>
 * @brief 世界标准地理坐标(WGS-84) 转换成 中国国测局地理坐标(GCJ-02)<火星坐标>
 *
 * ####只在中国大陆的范围的坐标有效,以外直接返回世界标准坐标
 */
public static LatLng wgs84ToGcj02(LatLng location) {
    return gcj02Encrypt(location.latitude, location.longitude);
}

/**
 * @param location 中国国测局地理坐标(GCJ-02)
 * @return 世界标准地理坐标(WGS-84)
 * @brief 中国国测局地理坐标(GCJ-02) 转换成 世界标准地理坐标(WGS-84)
 *
 * ####此接口有1-2米左右的误差,需要精确定位情景慎用
 */
public static LatLng gcj02ToWgs84(LatLng location) {
    return gcj02Decrypt(location.latitude, location.longitude);
}

/**
 * @param location 世界标准地理坐标(WGS-84)
 * @return 百度地理坐标(BD-09)
 * @brief 世界标准地理坐标(WGS-84) 转换成 百度地理坐标(BD-09)
 */
public static LatLng wgs84ToBd09(LatLng location) {
    LatLng gcj02Pt = gcj02Encrypt(location.latitude, location.longitude);
    return bd09Encrypt(gcj02Pt.latitude, gcj02Pt.longitude);
}

/**
 * @param location 中国国测局地理坐标(GCJ-02)<火星坐标>
 * @return 百度地理坐标(BD-09)
 * @brief 中国国测局地理坐标(GCJ-02)<火星坐标> 转换成 百度地理坐标(BD-09)
 */
public static LatLng gcj02ToBd09(LatLng location) {
    return bd09Encrypt(location.latitude, location.longitude);
}

/**
 * @param location 百度地理坐标(BD-09)
 * @return 中国国测局地理坐标(GCJ-02)<火星坐标>
 * @brief 百度地理坐标(BD-09) 转换成 中国国测局地理坐标(GCJ-02)<火星坐标>
 */
public static LatLng bd09ToGcj02(LatLng location) {
    return bd09Decrypt(location.latitude, location.longitude);
}

/**
 * @param location 百度地理坐标(BD-09)
 * @return 世界标准地理坐标(WGS-84)
 * @brief 百度地理坐标(BD-09) 转换成 世界标准地理坐标(WGS-84)
 *
 * ####此接口有1-2米左右的误差,需要精确定位情景慎用
 */
public static LatLng bd09ToWgs84(LatLng location) {
    LatLng gcj02 = bd09ToGcj02(location);
    return gcj02Decrypt(gcj02.latitude, gcj02.longitude);
}

public static class LatLng {
    public double latitude;
    public double longitude;

    public LatLng(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public LatLng() {
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
}
}