欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-06-24 12:11:24
1、配置app获取位置信息权限

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)
            }

        })

 

本文地址:https://blog.csdn.net/u010368726/article/details/107179878