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

获取位置信息

程序员文章站 2022-04-03 12:29:33
...

添加权限:

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

动态权限

// 检查权限
int permission1 = ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.ACCESS_COARSE_LOCATION);
int permission2 = ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION);
// 申请权限
if (permission1 == -1 && permission2 == -1) {
    ActivityCompat.requestPermissions(this,new String[{Manifest.permission.ACCESS_COARSE_LOCATION,
    Manifest.permission.ACCESS_FINE_LOCATION},12);
}        

获取位置信息:

Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(gpsLocation != null) {
    Log.e(TAG,"GPS : 经度 == " + gpsLocation.getLongitude() + "     纬度 == " + gpsLocation.getLatitude());
} else {
    Location netWorkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if(netWorkLocation != null) {
        Log.e(TAG,"NetWork : 经度 == " + netWorkLocation .getLongitude() +
                                "     纬度 == " + netWorkLocation .getLatitude());
    }
}

根据经纬度去请求百度地图或者高德地图的WebApi获取位置信息:

百度地图
百度地图请求返回错误:{"status":102,"message":"MCODE参数不存在,mobile类型mcode参数必需"}

解决方案:
1.给接口传入一个安全码的参数
http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=94Tmshjhp03oul7xy95Gu3wwHkjGZvkk&mcode=EE:0C:C8:50:54:53:96:5A:55:8C:23:2F:93:7E:EB:AE:D8:C8:1B:F1;com.example.tangdekun.androidannotationsdemo
斜体部分为安全码参数设置
2.安全码的获取
在百度开发者平台的“我的应用”进入创建的应用即可看到安全码