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

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

技术栈

Appgallery connect

开发准备

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

功能分析

地图的展示,我们需要在管理中心先给我们对应的应用开启地图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=false
  permissionController:CustomDialogController=new CustomDialogController({
    builder:PermissionDialogWidget({
      titleText:"权限说明",
      contentText: 'xxx想要申请位置权限,用于地址选择等功能。同意该权限后,选择地址时会复用此权限,不会重新申请,不授权上述权限,不影响APP其他功能使用。',
    }),
    alignment: DialogAlignment.Top,
  })
  @State locationInfo:geoLocationManager.ReverseGeoCodeRequest|null=null
  aboutToAppear(): void {
    try {
      let locationEnabled = geoLocationManager.isLocationEnabled();

      if (locationEnabled) {
        this.addressSetting=true
        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);
        });

      }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=true
          this.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=false
          this.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();
    }
  }


}
相关文章
|
3天前
《仿盒马》app开发技术分享-- 确认订单页(数据展示)(29)
上一节我们实现了地址的添加,那么有了地址之后我们接下来的重点就可以放到订单生成上了,我们在购物车页面,点击结算会跳转到一个 订单确认页面,在这个页面我们需要有地址选择、加购列表展示、价格计算、优惠计算、商品数量展示等信息。
18 3
|
3天前
|
存储 缓存 前端开发
《仿盒马》app开发技术分享-- 用户登录页(业务逻辑)(21)
上一节我们实现了静态的用户登录页,这一节我们需要给他添加上业务逻辑,实现跟云数据库的互通,同时跟整个应用关联起来,因为我们还没有实现用户的注册页面,所以这里我们在云数据库的用户数据插入暂时先不做同用户名的校验,我们在云端先插入几条数据,暂时专注于查询即可
18 5
|
3天前
|
定位技术
《仿盒马》app开发技术分享-- 地图选点(27)
上一节我们实现了地图的简单展示,这一节我们要实现的内容是,根据展示的地图,实现当前定位功能,当前位置的poi地址功能,以及列表的展示,给地图添加标记,展示自己的当前定位
21 4
|
3天前
|
数据安全/隐私保护
《仿盒马》app开发技术分享-- 用户登陆页面(静态)(20)
上一节我们实现了个人中心页面的静态展示,项目进行到这里呢,我们也是时候添加用户相关的内容了, 因为到了后期,我们的数据都是跟用户绑定的,各个用户之间的数据并不互通,现在为了实现我们的用户绑定制度,我们需要给应用添加一个用户登陆的入口的
17 4
|
3天前
《仿盒马》app开发技术分享-- 个人中心页面(19)
上一节我们实现了分类页面的所有联动效果,这一节我们要开始完成一个新的页面,这个页面是我们主界面的第四个板块,就是个人中心页面。在这个模块,我们可以显示一些用户信息,以及用户相关的各类功能的入口
17 4
|
3天前
|
JSON 数据格式
《仿盒马》app开发技术分享-- 分类右侧商品列表(18)
上一节我们实现了分类页左侧二级分类列表功能,并实现了顶部列表&弹窗跟左侧列表的联动,这一节我们需要在它们联动的基础上继续添加右侧列表的联动效果
20 4
|
3天前
|
JSON 数据挖掘 数据格式
《仿盒马》app开发技术分享-- 分类左侧列表(17)
上一节我们实现了分类页面的顶部导航栏全选弹窗列表,并实现了跟顶部列表的点击选中联动效果,这一节我们要实现的功能是,分类模块的左侧列表,它同样也需要跟弹窗列表的点击,顶部列表的点击有联动的效果
16 4
|
3天前
|
数据库
《仿盒马》app开发技术分享-- 确认订单页(业务逻辑)(30)
上一节我们实现了确认订单页的页面绘制和价格计算优惠计算,订单列表展示等功能,这一节我们来实现确认订单页的整个业务逻辑。首先我们要实现的就是地址的选择,然后把我们计算的价格,商品列表等数据保存起来,然后我们开始创建订单表实体类等,把这些数据提交到订单表中
19 3
|
3天前
|
存储 定位技术 数据库
《仿盒马》app开发技术分享-- 新增地址(28)
上一节我们实现了地图选点,获取当前位置,在地图上添加标记,根据当前的定位获取poi地址列表等功能,这些全部都为了我们这一节而铺垫,这一节我们要实现的是新增地址,把我们的用户信息,填写收件人、门牌号、手机号、经纬度、详细地址等信息添加到我们的云数据库中,然后在地址查询列表里展示出来。
16 2
|
3天前
|
前端开发
《仿盒马》app开发技术分享-- 个人中心页or静态头像选择(业务逻辑)(22)
上一节我们实现了登录页面的业务逻辑,并且成功的实现了数据的查询,同时我们新增了用户首选项的工具类,现在主界面往登录页面跳转,登录成功后我们关闭登录页面,这时候我们就会回到个人中心页面,那么现在我们的业务逻辑是一种什么样的形式?登录成功后我们需要显示用户的信息,并且在下次登录时依旧展示个人信息。同时我们还新增了一个头像选择的静态弹窗,丰富个人信息页面
15 1

热门文章

最新文章

OSZAR »