根据Android自带的API获取经纬度,然后通过经纬度获取当前位置信息

26 篇文章 1 订阅
1 篇文章 0 订阅

1、配置app获取位置信息权限

    <!-- 允许程序访问CellID或WiFi热点来获取粗略的位置 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <!-- 用于访问GPS定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

2、获取经纬度工具类

public class LocationUtil {

    public static void getCurrentLocation(Context context, LocationCallBack locationCallBack) {
        if (locationCallBack == null) {
            return;
        }
        if (context == null) {
            locationCallBack.onFail("请确保传入的参数context不为null");
        }
        //如果系统版本号在23及其以上则检查权限
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(context, Manifest.permission_group.LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationCallBack.onFail("请确保已经获取定位权限");
        }
        //获取LocationManager对象
        LocationManager locationM = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //实例化MyLocationListener
        MyLocationListener locationListener = new MyLocationListener(locationM, locationCallBack);
        //配置Criteria耗电低
        Criteria cri = new Criteria();
        cri.setPowerRequirement(Criteria.POWER_LOW);
        // 获取可用的provider,第二个参数标识 provider是否可用.
        String bestProvider = locationM.getBestProvider(cri, true);

        if (!TextUtils.isEmpty(bestProvider)) {
            LogUtil.e("bestProvider = " + bestProvider + "可用");
            locationM.requestLocationUpdates(bestProvider, 0, 0, locationListener);
        } else if (locationM.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            LogUtil.e(LocationManager.NETWORK_PROVIDER + "可用");
            locationM.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        } else if (locationM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            LogUtil.e(LocationManager.GPS_PROVIDER + "可用");
            locationM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        } else {
            //定位不可用,提示打开GPS
            LogUtil.e("定位不可用,提示打开GPS");
            locationCallBack.onFail("无可用的定位方式,请打开GPS");
        }
    }

    /**
     * LocationListener 的实现类
     */
    private static class MyLocationListener implements LocationListener {
        private LocationManager mLocationManager;
        private LocationCallBack mLocationCallBack;

        public MyLocationListener(LocationManager locationManager, LocationCallBack locationCallBack) {
            this.mLocationManager = locationManager;
            this.mLocationCallBack = locationCallBack;
        }

        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                if (mLocationCallBack != null) {
                    mLocationCallBack.onSuccess(location);
                }
                if (mLocationManager != null) {
                    mLocationManager.removeUpdates(this);
                }
            } else {
                if (mLocationCallBack != null) {
                    mLocationCallBack.onFail("location == null");
                }
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    }

    /**
     * 定位结果回调
     */
    public interface LocationCallBack {
        /**
         * 定位成功
         *
         * @param location
         */
        void onSuccess(Location location);

        /**
         * 定位失败
         *
         * @param msg
         */
        void onFail(String msg);
    }

}

3、根据经纬度获取位置信息工具类

/**
 * 根据经纬度获取地址信息
 */
public class GetAddressUtil {
    Context context;

    public GetAddressUtil(Context context) {
        this.context = context;
    }

    public String getAddress(double lnt, double lat) {

        Geocoder geocoder = new Geocoder(context);
        boolean falg = geocoder.isPresent();
        LogUtil.e("the falg is " + falg);
        StringBuilder stringBuilder = new StringBuilder();
        try {

            //根据经纬度获取地理位置信息---这里会获取最近的几组地址信息,具体几组由最后一个参数决定
            List<Address> addresses = geocoder.getFromLocation(lat, lnt, 1);

            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    //每一组地址里面还会有许多地址。这里我取的前2个地址。xxx街道-xxx位置
                    if (i == 0) {
                        stringBuilder.append(address.getAddressLine(i)).append("-");
                    }

                    if (i == 1) {
                        stringBuilder.append(address.getAddressLine(i));
                        break;
                    }
                }
                stringBuilder.append(address.getCountryName()).append("_");//国家
                stringBuilder.append(address.getFeatureName()).append("_");//周边地址
                stringBuilder.append(address.getLocality()).append("_");//市
//                stringBuilder.append(address.getPostalCode()).append("_");
//                stringBuilder.append(address.getCountryCode()).append("_");//国家编码
//                stringBuilder.append(address.getAdminArea()).append("_");//省份
//                stringBuilder.append(address.getSubAdminArea()).append("_");
//                stringBuilder.append(address.getThoroughfare()).append("_");//道路
//                stringBuilder.append(address.getSubLocality()).append("_");//香洲区
//                stringBuilder.append(address.getLatitude()).append("_");//经度
//                stringBuilder.append(address.getLongitude());//维度
                Log.d("thistt", "地址信息--->" + stringBuilder);
            }
        } catch (Exception e) {
            LogUtil.d("获取经纬度地址异常");
            e.printStackTrace();
        }
        return stringBuilder.toString();

    }


}

4、使用

LocationUtil.getCurrentLocation(this, object : LocationUtil.LocationCallBack {

            override fun onSuccess(location: Location) {
                val s = GetAddressUtil(this@MainActivity).getAddress(
                    location.longitude,
                    location.latitude
                )
                LogUtil.e(s)
            }

            override fun onFail(msg: String) {
                LogUtil.e(msg)
            }

        })

 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值