当前位置: 首页 > news >正文

【HarmonyOS Next】地图使用详解(三)标点定位问题

背景

在使用geoLocationManager的getCurrentLocation方法获得的用户定位经纬度的坐标系为 WGS84 ,但是mapkit使用的是GCJ02坐标系。因此,我们在使用获取用户经纬度然后直接生成标记时,会出现坐标偏移问题。如下:
在这里插入图片描述

解决方案

使用map.convertCoordinateSync方法,对已有的经纬度进行坐标系转换,生成GCJ02坐标系下的经纬度数值。
其中this.LocationLongitude和this.LocationLatitude都是viewmodel类中定义的经纬度。

直接获取经纬度代码

  /*** 更新用户定位*/public async UpdateLocation() {try {const result = await geoLocationManager.getCurrentLocation();this.LocationLongitude = result.longitude;this.LocationLatitude = result.latitude;} catch (err) {console.info("VM", "errCode:" + JSON.stringify(err));}}

获取转换后经纬度代码

public async UpdateLocationByConvert() {try {const result = await geoLocationManager.getCurrentLocation();let wgs84Position: mapCommon.LatLng = {latitude: result.latitude,longitude: result.longitude};let gcj02Position: mapCommon.LatLng =map.convertCoordinateSync(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, wgs84Position);this.LocationLongitude = gcj02Position.longitude;this.LocationLatitude = gcj02Position.latitude;} catch (err) {console.info("VM", "errCode:" + JSON.stringify(err));}}

实现效果:
请添加图片描述

完整代码

View

import { MapComponent } from "@kit.MapKit"
import { MapBlogViewModel } from "../ViewModels/MapBlogViewModel"@Entry
@ComponentV2
export struct MapBlogDemo {@Local MapVM: MapBlogViewModel = new MapBlogViewModel()aboutToAppear(): void {}build() {RelativeContainer() {MapComponent({mapOptions: this.MapVM.MapOption,mapCallback: this.MapVM.MapCallBack}).width("100%").height('70%').id("Map")Column({ space: 10 }) {Button("在我的位置创造一个标点").onClick(() => {this.MapVM.CreateLocationMarkerEvent();})Button("在我的位置创造一个转换后的标点").onClick(async () => {await this.MapVM.UpdateLocationByConvert();this.MapVM.CreateLocationMarkerEvent();})}.width("100%").height('30%').alignRules({top: { anchor: "Map", align: VerticalAlign.Bottom },bottom: { anchor: "__container__", align: VerticalAlign.Bottom }})}.height('100%').width('100%')}
}

ViewModel

import { map, mapCommon, sceneMap } from "@kit.MapKit"
import { AsyncCallback } from "@kit.BasicServicesKit"
import { geoLocationManager } from "@kit.LocationKit"
import { common } from "@kit.AbilityKit"
import { trustedAppService } from "@kit.DeviceSecurityKit"@ObservedV2
export class MapBlogViewModel {/*** 地图初始化参数设置*/@Trace MapOption?: mapCommon.MapOptions/*** 地图回调方法*/MapCallBack?: AsyncCallback<map.MapComponentController>/*** 地图控制器*/@Trace MapController?: map.MapComponentController/*** 地图监听管理器*/@Trace MapEventManager?: map.MapEventManager/*** 当前位置的维度*/public LocationLatitude: number = 39.9;/*** 当前位置的经度*/public LocationLongitude: number = 116.4;/*** 缩放数值*/public ZoomNumber: number = 20/*** 定位标记*/@Trace LocationMarker?: map.Markerconstructor() {this.MapOption = {//相机位置position: {target: {latitude: 39.9,longitude: 116.4},zoom: this.ZoomNumber},//地图类型mapType: mapCommon.MapType.STANDARD,//地图最小图层,默认值为2minZoom: 2,//地图最大图层,默认值为20maxZoom: 20,//是否支持旋转手势rotateGesturesEnabled: true,//是否支持滑动手势scrollGesturesEnabled: true,//是否支持缩放手势zoomGesturesEnabled: true,//是否支持倾斜手势tiltGesturesEnabled: true,//是否展示缩放控件zoomControlsEnabled: true,//是否展示定位按钮myLocationControlsEnabled: true,//是否展示指南针控件compassControlsEnabled: true,//是否展示比例尺scaleControlsEnabled: false,//是否一直显示比例尺,只有比例尺启用时该参数才生效。alwaysShowScaleEnabled: false};this.MapCallBack = async (err, mapController) => {if (!err) {this.MapController = mapController;//地图监听时间管理器this.MapEventManager = this.MapController.getEventManager();//启用我的位置图层this.MapController.setMyLocationEnabled(true);this.UpdateLocation().then(() => {});}}this.MoveCamera(this.LocationLatitude, this.LocationLongitude)}/*** 创建我的位置定位标记*/public async CreateLocationMarkerEvent() {let markerKey: string = 'DirectionKey';// Marker初始化参数let markerOptions: mapCommon.MarkerOptions = {position: {latitude: this.LocationLatitude,longitude: this.LocationLongitude},rotation: 0,visible: true,zIndex: 0,alpha: 1,anchorU: 0.5,anchorV: 1,clickable: false,draggable: false,flat: false,icon: "LocationIcon.svg",infoWindowAnchorU: 0,infoWindowAnchorV: 0};if (this.MapController) {// 创建Markerthis.LocationMarker = await this.MapController.addMarker(markerOptions);//设置标记可以拖拽this.LocationMarker.setDraggable(false);// 设置信息窗的标题// this.LocationMarker.setTitle(markerKey);// 设置标记可点击this.LocationMarker.setClickable(false);// 设置信息窗的锚点位置this.LocationMarker.setInfoWindowAnchor(1, 1);this.MoveCamera(this.LocationLatitude, this.LocationLongitude);}}/*** 展示地点选取页,更新标记地点*/public async ShowChoosingLocation() {let locationChoosingOptions: sceneMap.LocationChoosingOptions = {// 地图中心点坐标location: { latitude: this.LocationLatitude, longitude: this.LocationLongitude },language: 'zh_cn',// 展示搜索控件searchEnabled: true,// 展示附近PoishowNearbyPoi: true};// 拉起地点选取页let result: sceneMap.LocationChoosingResult =await sceneMap.chooseLocation(getContext(this) as common.UIAbilityContext, locationChoosingOptions);this.LocationLatitude = result.location.latitude;this.LocationLongitude = result.location.longitude;animateTo({duration: 500}, () => {this.MoveCamera(this.LocationLatitude, this.LocationLongitude);this.UpdateLocationMarker(result.location);})}/*** 更新定位位置* @param latLng*/private UpdateLocationMarker(latLng: mapCommon.LatLng) {if (this.LocationMarker) {this.LocationLatitude = latLng.latitude;this.LocationLongitude = latLng.longitude;this.LocationMarker.setPosition(latLng);}}/*** 更新用户定位*/public async UpdateLocation() {try {const result = await geoLocationManager.getCurrentLocation();this.LocationLongitude = result.longitude;this.LocationLatitude = result.latitude;} catch (err) {console.info("VM", "errCode:" + JSON.stringify(err));}}public async UpdateLocationByConvert() {try {const result = await geoLocationManager.getCurrentLocation();let wgs84Position: mapCommon.LatLng = {latitude: result.latitude,longitude: result.longitude};let gcj02Position: mapCommon.LatLng =map.convertCoordinateSync(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, wgs84Position);this.LocationLongitude = gcj02Position.longitude;this.LocationLatitude = gcj02Position.latitude;} catch (err) {console.info("VM", "errCode:" + JSON.stringify(err));}}/*** 移动视图相机* @param latitude 维度* @param longitude 经度*/public async MoveCamera(latitude: number, longitude: number) {if (this.MapController) {//将视图移动到标点位置let nwPosition = map.newCameraPosition({target: {latitude: latitude,longitude: longitude},zoom: 15})// 以动画方式移动地图相机this.MapController.animateCamera(nwPosition, 1000);}}
}

总结

上面地图遇到获取当前位置的经纬度的数值直接用来做标点时候,标点位置不正确的bug

http://www.xdnf.cn/news/256249.html

相关文章:

  • Java 中 Unicode 字符与字符串的转换:深入解析与实践
  • Go-web开发之帖子功能
  • 纯前端Word文档在线预览工具
  • Fedora升级Google Chrome出现GPG check FAILED问题解决办法
  • PyTorch_创建张量
  • 爱胜品ICSP YPS-1133DN Plus黑白激光打印机报“自动进纸盒进纸失败”处理方法之一
  • 解决Flutter项目中Gradle构建Running Gradle task ‘assembleDebug‘卡顿问题的终极指南
  • 【AI面试准备】元宇宙测试:AI+低代码构建虚拟场景压力测试
  • InnoDB索引的原理
  • 模型上下文协议(MCP)
  • 学习记录:DAY22
  • 数字智慧方案5873丨智慧交通设计方案(57页PPT)(文末有下载方式)
  • 动态库与静态库的区别
  • 内置类型成员变量的初始化详解
  • PostgreSQL 的 VACUUM 与 VACUUM FULL 详解
  • 6.DOS
  • 数字世界的“私人车道“:网络切片如何用Python搭建专属通信高速路?
  • 情境领导理论——AI与思维模型【89】
  • 单片机-STM32部分:0、学习资料汇总
  • RISCV的smstateen-ssstateen扩展
  • Flutter——数据库Drift开发详细教程(二)
  • 使用python爬取百度搜索中关于python相关的数据信息
  • 重构编程范式:解码字节跳动 AI 原生 IDE Trae 的技术哲学与实践价值
  • 【数据库】四种连表查询:内连接,外连接,左连接,右连接
  • 【Vue】Vue与UI框架(Element Plus、Ant Design Vue、Vant)
  • 传奇各职业/战士/法师/道士手套/手镯/护腕/神秘腰带爆率及出处产出地/圣战/法神/天尊/祈祷/虹魔/魔血
  • Codex CLI轻量级 AI 编程智能体 :openai又放大招了
  • 西游记4:从弼马温到齐天大圣;太白金星的计划;
  • P1308 统计单词数详解
  • 关于CSDN创作的常用模板内容