进入高德平台创建应用获取key,下载sdk。这边我只需要定位
AMap_Location_V4.2.0_20180809.jar
放入libs
在Manifest里面配置
<!--高德地图定位-->
<meta-data android:name="com.amap.api.v2.apikey" android:value="913e56****************6639f38">
</meta-data>
<service android:name="com.amap.api.location.APSService"></service>
基本配置完毕。
接下来创建LocationUtils
注释也很清楚
public class LocationUtils {
private static AMapLocationClient mlocationClient;
//声明mLocationOption对象
public static AMapLocationClientOption mLocationOption = null;
public static AMapLocation sLocation = null;
public static void init(Context context) {
mlocationClient = new AMapLocationClient(context);
//初始化定位参数
mLocationOption = new AMapLocationClientOption();
//设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
mLocationOption.setInterval(2000);
//设置定位参数
mlocationClient.setLocationOption(mLocationOption);
}
public interface MyLocationListener {
void result(AMapLocation location);
}
// 获取之前定位位置,如果之前未曾定位,则重新定位
public static void getLocation(MyLocationListener listener) {
if (sLocation == null) {
getCurrentLocation(listener);
} else {
listener.result(sLocation);
}
}
// 获取当前位置,无论是否定位过,重新进行定位
public static void getCurrentLocation(final MyLocationListener listener) {
if (mlocationClient == null) {
return;
}
// 设置定位监听
mlocationClient.setLocationListener(new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation location) {
if (location != null) {
//定位成功,取消定位
mlocationClient.stopLocation();
sLocation = location;
listener.result(location);
} else {
//获取定位数据失败
}
}
});
// 启动定位
mlocationClient.startLocation();
}
public static void destroy() {
mlocationClient.onDestroy();
}
}
如何调用?
先全局初始化,创建一个MyApplication类进行初始化。
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
LocationUtils.init(this);
}
}
在需要调用的地方直接调用
如:
LocationUtils.getLocation(new LocationUtils.MyLocationListener() {
@Override
public void result(AMapLocation location) {
if (location.getErrorCode() == 0) {
//针对location进行相关操作,如location.getCity(),无需验证location是否为null;
String city = location.getCity();
String country = location.getCountry();
String cityCode = location.getCityCode();
} else {
Log.e("AmapError", "location Error, ErrCode:"
+ location.getErrorCode() + ", errInfo:"
+ location.getErrorInfo());
}
}
});
这样一个定位的utils完成。~~
本文参考:https://www.aliyun.com/jiaocheng/29390.html
只是稍微整理了一下。~~