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

《仿盒马》app开发技术分享-- 原生地图展示(端云一体)

开发准备

上一节我们实现了获取当前用户的位置,并且成功的拿到了经纬度,这一节我们就要根据拿到的经纬度,结合我们其他的知识点来实现地图的展示。

功能分析

地图的展示,我们需要在管理中心先给我们对应的应用开启地图api功能,否则是不能展示的,其次是我们要配置自签,不配置的话也是无法使用地图功能,然后我们还需要注意应用是否开启了联网权限,如果这些都已经完成,那么我们在地图显示之前还需要进行权限时候获取的校验

代码实现

首先我们在进入页面之前判断是否已经开启了定位权限
bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {

    }).catch((err: BusinessError) => {hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed. Cause: %{public}s', err.message);});

要实现这个功能我们还需要获取app的acctokenid
bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
atManager.checkAccessToken(data.appInfo.accessTokenId, ‘ohos.permission.LOCATION’).then((status: abilityAccessCtrl.GrantStatus) => {
if (status==0) {
this.addressSetting=true
this.locationKey=true
this.reqPermissionsFromUser(permissions);
}
}).catch((err: BusinessError) => {
console.error(checkAccessToken fail, err->${JSON.stringify(err)});
});
}).catch((err: BusinessError) => {
hilog.error(0x0000, ‘testTag’, ‘getBundleInfoForSelf failed. Cause: %{public}s’, err.message);
});
这时候我们就通过反悔的status进行判断,当status等于0,我们就执行reqPermissionsFromUser,获取当前的位置经纬度,然后在里边实现地图参数的初始化和回调

this.mapOptions = {
position: {
target: {
latitude: locationInfo.latitude,
longitude: locationInfo.longitude
},
zoom: 10
}
};
this.callback = async (err, mapController) => {
if (!err) {
this.mapController = mapController;
this.mapEventManager = this.mapController.getEventManager();
let callback = () => {
console.info(“TAG”, on-mapLoad);
}
this.mapEventManager.on(“mapLoad”, callback);
}
};
都实现之后我们再添加对应的生命周期方法
onPageShow(): void {
if (this.mapController) {
this.mapController.show();
}
}

onPageHide(): void {
if (this.mapController) {
this.mapController.hide();
}
}
到这里我们的地图展示就实现了,我们执行一下代码看看效果
在这里插入图片描述
可以看到我们的地图已经成功展示出来了,完整代码如下

import { MapComponent, mapCommon, map } from '@kit.MapKit';
import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import PermissionDialogWidget from '../dialog/PermissionDialogWidget';
import { geoLocationManager } from '@kit.LocationKit';
import { abilityAccessCtrl, bundleManager, common, Permissions } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';const permissions: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION','ohos.permission.LOCATION'];
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
@Entry
@Component
struct PushAddressPage {private mapOptions?: mapCommon.MapOptions;private callback?: AsyncCallback<map.MapComponentController>;private mapController?: map.MapComponentController;private mapEventManager?: map.MapEventManager;@State flag:boolean=false@State ss:number=0@State  locationKey:boolean=false@State  addressSetting:boolean=falsepermissionController:CustomDialogController=new CustomDialogController({builder:PermissionDialogWidget({titleText:"权限说明",contentText: '仿盒马想要申请位置权限,用于地址选择等功能。同意该权限后,选择地址时会复用此权限,不会重新申请,不授权上述权限,不影响APP其他功能使用。',}),alignment: DialogAlignment.Top,})@State locationInfo:geoLocationManager.ReverseGeoCodeRequest|null=nullaboutToAppear(): void {try {let locationEnabled = geoLocationManager.isLocationEnabled();if (locationEnabled) {this.addressSetting=truebundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();atManager.checkAccessToken(data.appInfo.accessTokenId, 'ohos.permission.LOCATION').then((status: abilityAccessCtrl.GrantStatus) => {if (status==0) {this.addressSetting=truethis.locationKey=truethis.reqPermissionsFromUser(permissions);}}).catch((err: BusinessError) => {console.error(`checkAccessToken fail, err->${JSON.stringify(err)}`);});}).catch((err: BusinessError) => {hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed. Cause: %{public}s', err.message);});}else {this.addressSetting=false}} catch (err) {console.error("errCode:" + err.code + ", message:"  + err.message);}}build() {if (this.flag){Column() {Stack({alignContent:Alignment.Bottom}){Column(){MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback }).width('100%').height('100%');}.layoutWeight(1)if (this.addressSetting&&!this.locationKey){Row(){Text().width(40)Text("定位未开启").fontColor(Color.Black)Text("开启定位").fontColor(Color.White).backgroundColor(Color.Pink).borderRadius(10).padding(10).onClick(()=>{this.reqPermissionsFromUser(permissions);this.permissionController.open();})}.padding(10).borderRadius(5).margin({bottom:30}).backgroundColor('#33000000').justifyContent(FlexAlign.SpaceAround).width('90%')}}.backgroundColor(Color.White).height('100%').width('100%')}}}reqPermissionsFromUser(permissions: Array<Permissions>): void {let context = getContext(this) as common.UIAbilityContext;let atManager = abilityAccessCtrl.createAtManager();atManager.requestPermissionsFromUser(context, permissions).then((data) => {let grantStatus: Array<number> = data.authResults;let length: number = grantStatus.length;for (let i = 0; i < length; i++) {if (grantStatus[i] === 0) {this.locationKey=truethis.permissionController.close()let request: geoLocationManager.SingleLocationRequest = {'locatingPriority': geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,'locatingTimeoutMs': 10000}try {geoLocationManager.getCurrentLocation(request).then((result) => {console.log('current location: ' + JSON.stringify(result));let locationInfo:geoLocationManager.ReverseGeoCodeRequest=result;this.mapOptions = {position: {target: {latitude: locationInfo.latitude,longitude: locationInfo.longitude},zoom: 10}};this.callback = async (err, mapController) => {if (!err) {this.mapController = mapController;this.mapEventManager = this.mapController.getEventManager();let callback = () => {console.info("TAG", `on-mapLoad`);}this.mapEventManager.on("mapLoad", callback);}};this.flag=true}).catch((error:BusinessError) => {console.error('promise, getCurrentLocation: error=' + JSON.stringify(error));});} catch (err) {console.error("errCode:" + JSON.stringify(err));}} else {this.locationKey=falsethis.permissionController.close()return;}}}).catch((err:Error) => {console.error(`requestPermissionsFromUser failed, code is ${err.name}, message is ${err.message}`);})}aboutToDisappear() {this.permissionController!=undefined// 将dialogController置空}onPageShow(): void {if (this.mapController) {this.mapController.show();}}onPageHide(): void {if (this.mapController) {this.mapController.hide();}}}
http://www.xdnf.cn/news/8730.html

相关文章:

  • 【Python】1. 基础语法(1)
  • webpack优化方法
  • 学习日记-day15-5.25
  • 云原生安全之HTTP协议:从基础到实战的安全指南
  • JavaSE核心知识点03高级特性03-05(注解)
  • 后经济时代开源链动2+1模式AI智能名片S2B2C商城小程序驱动零售企业转型研究
  • JAVA 项目中 maven pom.xml 和 properties 配置文件、spring 配置文件,以及环境变量的关系
  • 《STL--list的使用及其底层实现》
  • 基于aspnet,微信小程序,mysql数据库,在线微信小程序汽车故障预约系统
  • Win11 系统登入时绑定微软邮箱导致用户名欠缺
  • 【TDengine源码阅读】taosMemoryDbgInit函数
  • 基于MATLAB实现传统谱减法以及两种改进的谱减法(增益函数谱减法、多带谱减法)的语音增强
  • 全面理解类和对象(下)
  • 5.25本日总结
  • 计算机网络-WebSocket/DNS/Cookie/Session/Token/Jwt/Nginx
  • DAY36
  • GitLab-CI简介
  • 单链表的排序
  • Collection集合遍历的三种方法
  • multiprocessing多进程使用案例
  • 用神经网络对信贷项目进行预测
  • java三种常见设计模式,工厂、策略、责任链
  • 原生php单元测试
  • bun全栈开发尝鲜:用bun-react-template实现Markdown文章展示
  • removeIf() 方法,结合 Lambda 表达式
  • 鸿蒙仓颉开发语言实战教程:页面跳转和传参
  • WORD 转 PDF 工具:排版 / 图片 / 表格批量转换提升办公效率
  • Acrobat 中 JavaScript 为 PDF 带来的交互
  • 篇章二 数据结构——前置知识(二)
  • C# 正则表达式