鸿蒙运动健康实战:自定义定位箭头跟随手机方向旋转

张开发
2026/4/14 0:37:51 15 分钟阅读

分享文章

鸿蒙运动健康实战:自定义定位箭头跟随手机方向旋转
告别系统蓝点实现高精度自定义定位箭头实时响应手机朝向为运动轨迹应用增添使用交互体验。完整源码SportTrackDemo在上一节中我们已经实现了运动轨迹记录、后台长时任务申请等功能。但系统默认的“我的位置”蓝点带有光圈。虽然可以自定义样式但是无法实现箭头跟随手机方向旋转。本文将手把手教你如何关闭系统定位图层用自定义 Marker 替换并通过传感器获取设备方向让箭头实时指向手机朝向。一、最终效果二、实现思路关闭系统定位图层setMyLocationEnabled(false)避免显示默认蓝点。自定义定位 Marker创建带箭头的 Marker锚点设为中心便于旋转。监听定位变化实时更新 Marker 的位置。监听方向传感器获取设备方位角0~360°0北顺时针。实时旋转调用marker.setRotation(angle)。三、核心代码实现3.1 在MapManager中添加自定义定位箭头管理// MapManager.etsprivatemyLocationMarker?:map.Marker;/** * 更新自定义定位箭头的位置和旋转角度 * param lat 纬度GCJ02 * param lng 经度GCJ02 * param rotation 旋转角度0~360°0正北 */asyncupdateMyLocationMarker(lat:number,lng:number,rotation?:number):Promisevoid{if(!this.myLocationMarker){constoptions:mapCommon.MarkerOptions{position:{latitude:lat,longitude:lng},icon:$r(app.media.ic_location_arrow),// 箭头图标anchorU:0.5,anchorV:0.5,flat:false,// 面对相机旋转效果明显clickable:false};this.myLocationMarkerawaitthis.mapController?.addMarker(options);}else{this.myLocationMarker.setPosition({latitude:lat,longitude:lng});}if(rotation!undefined){this.myLocationMarker.setRotation(rotation);}}setMyLocationRotation(rotation:number):void{this.myLocationMarker?.setRotation(rotation);}removeMyLocationMarker():void{this.myLocationMarker?.remove();this.myLocationMarkerundefined;}关键点anchorU/V: 0.5确保旋转中心在图标中心。flat: false使图标始终面向相机旋转效果清晰。如果你使用的是“圆点箭头”组合图标例如一个圆点旁边带箭头且将锚点设为 (0.5, 0.5) 中心点那么圆点必须位于图标的几何中心箭头从中心向外延伸。否则旋转时圆点会偏离实际定位位置看起来“跑偏”。另外一种就是修改锚点 但是这是邪修法不合适。我不会设计图随便找了一个icon所以现在也是’跑偏的’。3.2 修改init方法关闭系统定位init(controller:map.MapComponentController):void{this.mapControllercontroller;controller.setMapType(mapCommon.MapType.STANDARD);// 关闭系统定位图层controller.setMyLocationEnabled(false);controller.setMyLocationControlsEnabled(false);}3.3 传感器管理类SensorManager单例import{sensor}fromkit.SensorServiceKit;/** * 方位角回调函数类型 * param azimuth 设备方向角单位度范围 0~3600°正北顺时针增加 */exporttypeAngleCallback(azimuth:number)void;// 传感器管理类exportclassSensorManager{privatestaticinstance:SensorManager;privatecallback?:AngleCallback;// 用户注册的回调privateisListening:booleanfalse;// 是否正在监听staticgetInstance():SensorManager{if(!SensorManager.instance){SensorManager.instancenewSensorManager();}returnSensorManager.instance;}// 开始监听设备方向方位角start(callback:AngleCallback,interval:number100_000_000):void{if(this.isListening){console.warn(传感器已在监听中请先 stop());return;}// 检查设备是否支持方向传感器try{// 推荐直接获取指定类型的传感器列表constsensorssensor.getSensorListSync();if(sensors.length0){console.error(设备不支持方向传感器无法获取方位角);return;}}catch(error){console.error(获取方向传感器列表失败:${JSON.stringify(error)});return;}this.callbackcallback;// 订阅方向传感器try{sensor.on(sensor.SensorId.ORIENTATION,(data:sensor.OrientationResponse){constazimuthdata.alpha;// 0~360°this.callback?.(azimuth);},{interval:interval});}catch(error){console.error(订阅方向传感器失败:${JSON.stringify(error)});return;}this.isListeningtrue;console.info(开始监听设备方向间隔${interval}ns);}stop():void{if(!this.isListening)return;try{sensor.off(sensor.SensorId.ORIENTATION);}catch(error){console.error(停止传感器监听失败:${JSON.stringify(error)});}finally{this.isListeningfalse;this.callbackundefined;console.info(停止传感器监听);}}}四、地图箭头指向与现实手机指向相反箭头指向与手机实际朝向相反或偏差90°/180°的问题原因有二传感器alpha定义0° 北顺时针增加。但某些设备的传感器可能返回相反方向例如北为180°。图标自身方向如果图标设计为指向右侧90°则需减去90°。通用修正公式letcorrectedazimuth;// 情况1完全相反 → 加180°corrected(azimuth180)%360;// 情况2镜像翻转 → 取反corrected(360-azimuth)%360;// 情况3偏某个固定角度corrected(azimuthoffset360)%360;我们的是第一种情况完全相反调试建议用系统指南针 App 对比记录手机朝北时打印的azimuth值。若朝北打印 0无需修正若打印 180则加180°。若朝北打印其他值使用(360 - azimuth) % 360。我在实际测试中发现设备返回的alpha正好与地图旋转角相反因此采用(azimuth 180) % 360解决了问题。未修正方向修正后方向地图页监听传感器的方位角并且记录下来页面初始化开始监听页面结束释放定图更新除传递坐标增加方位角。以下代码只专注更新自定义箭头位置完整代码仓库下载。// Index.etsimport{SensorManager}from../common/managers/SensorManager;import{MapManager}from../common/managers/MapManager;import{geoLocationManager}fromkit.LocationKit;Entry Component struct Index{privatemapManager:MapManagernewMapManager();privatecurrentAzimuth:number0;aboutToAppear(){// 启动方向传感器SensorManager.getInstance().start((azimuth){// 反转方向加上 180 度再模 360 不然方向正好相反constcorrected(azimuth180)%360;this.currentAzimuthcorrected;this.mapManager.setMyLocationRotation(corrected);});}// 定位与轨迹处理方法 privateonLocationUpdate(rawLoc:geoLocationManager.Location){if(!rawLoc.latitude||!rawLoc.longitude)return;// 立即更新地图上的蓝点// this.mapController?.setMyLocation(rawLoc);// 坐标转换constgcjMapManager.convertWgs84ToGcj02(rawLoc.latitude,rawLoc.longitude);// 更新自定义圆点this.mapManager.updateMyLocationMarker(gcj.latitude,gcj.longitude,this.currentAzimuth);}privateasyncmoveToMyLocationIfNeeded(){if(this.hasMovedToMyLocation)return;if(!this.hasLocationPermission){console.warn(无定位权限跳过移动相机);return;}try{if(!geoLocationManager.isLocationEnabled()){this.showToast(请开启设备位置服务);return;}// 优先使用缓存位置constlastLocationgeoLocationManager.getLastLocation();if(lastLocationlastLocation.latitudelastLocation.longitude){constgcjMapManager.convertWgs84ToGcj02(lastLocation.latitude,lastLocation.longitude);// 更新自定义定位箭头位置 当前方向this.mapManager.updateMyLocationMarker(gcj.latitude,gcj.longitude,this.currentAzimuth);this.moveCameraToPoint(gcj.latitude,gcj.longitude,SportConstants.MAP_ZOOM_LEVEL);this.hasMovedToMyLocationtrue;console.info(使用缓存位置移动相机);}constrequest:geoLocationManager.SingleLocationRequest{locatingPriority:geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,locatingTimeoutMs:SportConstants.SINGLE_LOCATION_TIMEOUT_MS};constlocationawaitgeoLocationManager.getCurrentLocation(request);this.mapController?.setMyLocation(location);constgcjMapManager.convertWgs84ToGcj02(location.latitude,location.longitude);this.moveCameraToPoint(gcj.latitude,gcj.longitude,SportConstants.MAP_ZOOM_LEVEL);this.hasMovedToMyLocationtrue;console.info(已移动到用户当前位置);}catch(error){console.error(定位失败,error);this.showToast(无法获取当前位置请点击开始运动后自动跟随,SportConstants.TOAST_DURATION_LONG);}}aboutToDisappear(){// 停止传感器释放资源SensorManager.getInstance().stop();this.mapManager.removeMyLocationMarker();this.stopTracking();}}五、完整流程图启动应用 ↓ 关闭系统定位图层 ↓ 创建自定义Marker箭头图标 ↓ 启动定位监听 → 更新Marker位置 ↓ 启动方向传感器 → 实时旋转Marker ↓ 用户转动手机 → 箭头同步旋转六、性能与功耗优化传感器间隔interval默认为 100ms100_000_000 ns既保证流畅又不过度耗电。可调整为game约20ms提升顺滑度。避免重复创建 Marker只在首次定位时创建后续复用。页面销毁时停止传感器在aboutToDisappear中调用SensorManager.stop()。七、总结通过关闭系统定位图层、自定义 Marker 并接入方向传感器我们实现了高精度、可自定义的定位箭头旋转效果。整个过程无需申请额外权限代码清晰性能优异。

更多文章