Android 获取位置信息(经纬度以及坐标)

首先第一步要添加权限

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

 

第二步是要获取权限

因为咱们的6.0及以上的版本把这一类的权限定义为敏感权限/危险权限,所以在6.0之后我们要去动态去获取权限,这一步就省略了 ,如果还有小伙伴还不知道去动态获取权限 翻看下我之前的博客

传送门

略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略略。

第三步就是直接封装个工具类 用的时候可以直接调用

新建一个 LocationUtils 类

public class LocationUtils {
    private LocationManager locationManager;
    static LocationUtils locationUtils;

    public static LocationUtils getInstance() {
        if (locationUtils == null) {
            locationUtils = new LocationUtils();
        }
        return locationUtils;
    }

    public ArrayList<String> getLocations(Context context) {
        ArrayList<String> strings=new ArrayList<>();
        if (!isOPenGPS(context)){
            Toast.makeText(context, "未开启定位,无法获取地理位置", Toast.LENGTH_SHORT).show();
            return strings;
        }

        String strLocation = "";
        DecimalFormat df = new DecimalFormat("#####0.0000");
        if (!checkPermission(context, permission.ACCESS_COARSE_LOCATION)) {
            Toast.makeText(context, "定位权限关闭,无法获取地理位置", Toast.LENGTH_SHORT).show();
        }
        try {
            //获取系统的服务,
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            //创建一个criteria对象
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            //设置不需要获取海拔方向数据
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            //设置允许产生资费
            criteria.setCostAllowed(true);
            //要求低耗电
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            String provider = locationManager.getBestProvider(criteria, true);
            Log.e("wqs", "Location Provider is " + provider);
            @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(provider);
            Log.w("wqs", "经纬度信息: " + location.getLatitude()+"---"+location.getLongitude());
            /**
             * 重要函数,监听数据测试
             * 位置提供器、监听位置变化的时间间隔(毫秒),监听位置变化的距离间隔(米),LocationListener监听器
             */
//           locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    lm.removeUpdates(locationListener);
//                }
//            },2000);

            //第一次获得设备的位置
            if (location != null) {
//                strLocation = df.format(location.getLatitude()) + "," + df.format(location.getLongitude());
                // 耗时操作
                strLocation += "" + getLocationAddress(context, location);
                if (strLocation.equals("")) {
                    strLocation += "" + convertAddress(context, location.getLatitude(), location.getLongitude());
                }
            }
            strings.add(strLocation);
            strings.add(location.getLatitude()+"/"+location.getLongitude());

        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }

    /**
     * @param latitude  经度
     * @param longitude 纬度
     * @return 详细位置信息 GeoCoder是基于后台backend的服务,因此这个方法不是对每台设备都适用。
     */
    public String convertAddress(Context context, double latitude, double longitude) {
        Geocoder mGeocoder = new Geocoder(context, Locale.getDefault());
        StringBuilder mStringBuilder = new StringBuilder();

        try {
            List<Address> mAddresses = mGeocoder.getFromLocation(latitude, longitude, 1);
            if (!mAddresses.isEmpty()) {
                Address address = mAddresses.get(0);
                mStringBuilder.append(address.getLocality()).append(address.getThoroughfare());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return mStringBuilder.toString();
    }

    private boolean checkPermission(Context context, permission permName) {
        int perm = context.checkCallingOrSelfPermission("android.permission." + permName.toString());
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    private enum permission {
        ACCESS_COARSE_LOCATION,
        ACCESS_FINE_LOCATION
    }

    private String getLocationAddress(Context mContext, Location location) {
        String addNow = "";
        Geocoder geoCoder = new Geocoder(mContext, Locale.CHINESE);
        try {
            List<Address> addresses = geoCoder.getFromLocation(
                    location.getLatitude(), location.getLongitude(),
                    1);
            Address address = addresses.get(0);
            Log.w("wqs", "远程获取定位全部为: " + address.toString());
            // Address[addressLines=[0:"中国",1:"北京市海淀区",2:"华奥饭店公司写字间中关村创业大街"]latitude=39.980973,hasLongitude=true,longitude=116.301712]

            if (address.getAddressLine(0) != null && !address.getAddressLine(0).equals("")) {
                addNow = address.getAddressLine(0);
                Log.w("wqs", "获取成功第一种: " + addNow);
            } else if (addNow.equals("") && address.getFeatureName() != null && !address.getFeatureName().equals("")) {
                addNow = address.getLocality() + address.getFeatureName();
                Log.w("wqs", "获取成功第二种: " + addNow);
            } else {
                int maxLine = address.getMaxAddressLineIndex();
                if (maxLine >= 2) {
                    addNow = address.getAddressLine(1) + address.getAddressLine(2);
                } else {
                    addNow = address.getAddressLine(1);
                }
                Log.w("wqs", "获取成功第三种: " + addNow);
            }


        } catch (IOException e) {
            addNow = "";
            e.printStackTrace();
        }
        if (addNow.contains("null")) {
            addNow = addNow.replaceAll("null", "");
        }
        return addNow;
    }

    /**
     * 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    private boolean isOPenGPS(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // GPS定位
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 网络服务定位
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }
}

第四步,点赞 评论 加关注!!!

第四步,点赞 评论 加关注!!!

第四步,点赞 评论 加关注!!!

用法简单,直接调用即可

LocationUtils.getInstance().getLocations(context);

效果:

随码附上下载地址:LocationDemo.rar-交通文档类资源-CSDN下载

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jonly_W

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值