使用场景
该示例主要展示在同一个移动端页面内通过连续定位持续确定设备位置的同时,用户通过按钮(或其他)主动获取一次当前位置的场景。
用到产品
核心类/接口
类接口说明版本
AMapLocationClientOptionsetOnceLocation(Boolean b);设置单次定位接口V2.0.0版本起
setInterval(long time);设置连续定位时间间隔V2.0.0版本起
AMapLocationClientstartLocation();启动定位V2.0.0版本起
setLocationOption(mLocationOption);给定位客户端设置参数V2.0.0版本起
AMapLocationListeneronLocationChanged(AMapLocation amapLocation);监听器回调方法V2.0.0版本起
核心难点
分别创建单次、连续定位客户端以及监听器,这样可以有效的区分定位结果是来自持续定位还是来自单次定位。
1、分别创建定位客户端:
创建单次定位客户端:
AMapLocationClient locationClientSingle = new AMapLocationClient(this.getApplicationContext());
创建连续定位客户端:
AMapLocationClient locationClientContinue = new AMapLocationClient(this.getApplicationContext());
2、分别创建定位结果监听器:
单次定位的监听:
/**
* 单次客户端的定位监听
*/
AMapLocationListener locationSingleListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation location) {
}
};
locationClientSingle.setLocationListener(locationSingleListener);
连续定位的监听:
/**
* 连续客户端的定位监听
*/
AMapLocationListener locationContinueListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation location) {
}
};
locationClientContinue.setLocationListener(locationContinueListener);
3、分别设置定位行为:
设置单次定位的行为:
//获取一次定位结果:
//该方法默认为false。
locationClientSingleOption.setOnceLocation(true);
//关闭缓存机制
locationClientSingleOption.setLocationCacheEnable(false);
//给定位客户端对象设置定位参数
locationClientSingle.setLocationOption(locationClientSingleOption);
//启动定位
locationClientSingle.startLocation();
设置连续定位的行为:
//设置定位间隔,单位毫秒,默认为2000ms,最低1000ms。
locationClientContinueOption.setInterval(1000);
//给定位客户端对象设置定位参数
locationClientContinue.setLocationOption(locationClientContinueOption);
//启动定位
locationClientContinue.startLocation();