介绍
本示例展示了定位图标方向跟随手机指向转动的效果。
使用产品
Android 地图 SDK(该功能已经整合到地图SDK中)
核心类说明
1、TencentMap :地图核心类
2、 TencentLocationManager:用于访问腾讯定位服务的类, 腾讯定位服务可周期性向客户端提供位置更新
3、TencentLocationRequest:定位请求, 客户端使用本类指定定位周期等参数.
4、TencentLocation:地理位置
示例核心点讲解
1、获取手机sensor角度值并过滤
@Override
public void onSensorChanged(SensorEvent event) {
if (System.currentTimeMillis() - lastTime < TIME_SENSOR) {
return;
}
switch (event.sensor.getType()) {
case Sensor.TYPE_ORIENTATION: {
float x = event.values[0];
x += getScreenRotationOnPhone(mContext);
x %= 360.0F;
if (x > 180.0F)
x -= 360.0F;
else if (x < -180.0F)
x += 360.0F;
if (Math.abs(mAngle - x) < 3.0f) {
break;
}
mAngle = Float.isNaN(x) ? 0 : x;
if (mMarker != null) {
mMarker.setRotation(mAngle);
}
lastTime = System.currentTimeMillis();
}
}
}
2、获取当前手机屏幕旋转角度
/**
* 获取当前屏幕旋转角度
*
* @param context
* @return 0表示是竖屏; 90表示是左横屏; 180表示是反向竖屏; 270表示是右横屏
*/
public static int getScreenRotationOnPhone(Context context) {
final Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
switch (display.getRotation()) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 90;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return -90;
}
return 0;
}
3、定位回调成功处理Marker绘制
if (i == TencentLocation.ERROR_OK && locationChangedListener != null) {
Location location = new Location(tencentLocation.getProvider());
//设置经纬度以及精度
location.setLatitude(tencentLocation.getLatitude());
location.setLongitude(tencentLocation.getLongitude());
location.setAccuracy(tencentLocation.getAccuracy());
LatLng latLng = new LatLng(tencentLocation.getLatitude(), tencentLocation.getLongitude());
addMarker(latLng);
if(mSensorHelper!=null){
//定位图标旋转
mSensorHelper.setCurrentMarker(marker);
}
locationChangedListener.onLocationChanged(location);
}
注意点
实现上面效果之前需要先开启定位服务
//用于访问腾讯定位服务的类, 周期性向客户端提供位置更新
locationManager = TencentLocationManager.getInstance(this);
//设置坐标系
locationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);
//创建定位请求
locationRequest = TencentLocationRequest.create();
//设置定位周期(位置监听器回调周期)为3s
locationRequest.setInterval(3000);
//地图上设置定位数据源
mTencentMap.setLocationSource(this);
//设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
mTencentMap.setMyLocationEnabled(true);
