HarmonyOS 无法显示自己的位置图标

打开页面时,可以定位到当前的位置,但是不显示我的位置标志图片。

代码如下:

import { MapComponent, mapCommon, map } from '@kit.MapKit';
import { AsyncCallback, BusinessError } from '@ohos.base';
import { getLocation } from '../../../utils/LocationUtils';
import { LogUtils } from '../../../utils/LogUtils';
import statusBarUtils from '../../../utils/StatusBarUtils';
import showToast from '../../../utils/ToastUtils';
import { CommonTopBar } from '../../../views/CommonTopBar';


@Entry
@Component
struct SelectLocationMapPage {
  private TAG = "SelectLocationMapPage";
  @State mapOption: mapCommon.MapOptions | null = null;
  private callback?: AsyncCallback<map.MapComponentController>;
  private mapController?: map.MapComponentController;
  private myLocationButtonClick: Callback<void> = () => {

  }

  onPageShow(): void {
    statusBarUtils.setStatusBarContentColor()
  }

  aboutToAppear(): void {
    getLocation(getContext(this)).then(res => {
      this.mapOption = {
        position: {
          target: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          zoom: 15
        },
        myLocationControlsEnabled: true,
        tiltGesturesEnabled: true
      };
    }).catch((error: BusinessError) => {
      showToast(error.message)
    })

    // 地图初始化的回调
    this.callback = async (err, mapController) => {
      LogUtils.info(this.TAG, err?.message);
      if (!err) {
        this.mapController = mapController;
        this.onMapInit(mapController)
      }
    };

  }

  private async onMapInit(mapController: map.MapComponentController) {
    // 获取地图的控制器类,用来操作地图
    mapController.on("mapLoad", () => {
      LogUtils.info(this.TAG, `on-mapLoad`);
    });
    mapController.on("myLocationButtonClick", this.myLocationButtonClick);
    let style: mapCommon.MyLocationStyle = {
      anchorU: 0.5,
      anchorV: 1,
      icon: $r('app.media.ic_my_location'),
      displayType: mapCommon.MyLocationDisplayType.FOLLOW
    }
    await mapController.setMyLocationStyle(style)
  }

  aboutToDisappear(): void {
    this.mapController?.off("myLocationButtonClick", this.myLocationButtonClick);
  }

  build() {
    Column() {
      CommonTopBar()
      if (this.mapOption) {
        MapComponent({ mapOptions: this.mapOption, mapCallback: this.callback })
          .width('100%')
          .height(0)
          .layoutWeight(1)
      }
    }.width("100%")
    .height("100%")
  }
}
HarmonyOS
9天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

可以参考如下demo示例

import { map, mapCommon, MapComponent } from '@kit.MapKit';
import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { abilityAccessCtrl, bundleManager, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { geoLocationManager } from '@kit.LocationKit';
@Entry
@Component
struct HuaweiMyLocationDemo {
  //校验应用是否被授权定位权限,可以通过调用checkAccessToken()方法来校验当前是否已经授权。
  async checkPermission(): Promise<void> {
    let applyResult: boolean = false;
    const permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION','ohos.permission.INTERNET'];
    for(let permission of permissions) {
      let grantStatus: abilityAccessCtrl.GrantStatus = await this.checkAccessToken(permission);
      if(grantStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
        applyResult = true;
      }else {
        applyResult = false
      }
    }
    if(!applyResult) {
      this.requestPermissions();
    }else {
      //启用我的位置图层,mapController为地图操作类对象,获取方式详见地图呈现章节
      this.mapController?.setMyLocationEnabled(true);
      //启用我的位置按钮
      this.mapController?.setMyLocationControlsEnabled(true);
    }
  }
  //如果没有被授予定位权限,动态向用户申请授权
  requestPermissions(): void {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    atManager.requestPermissionsFromUser(getContext() as common.UIAbilityContext,['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION','ohos.permission.INTERNET'])
      .then((data: PermissionRequestResult) => {
        //启用我的位置图层
        this.mapController?.setMyLocationEnabled(true);
        //启用我的位置按钮
        this.mapController?.setMyLocationControlsEnabled(true);
      })
      .catch((err: BusinessError) => {
        console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`)
      })
  }


  async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
    //&#33719;&#21462;&#24212;&#29992;&#31243;&#24207;&#30340;accessTokenID
    let tokenId: number = 0;
    try {
      let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
      let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
      tokenId = appInfo.accessTokenId;
    } catch ( error ) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to get bundle info for self. Code is ${err.code},message is ${err.message}`)
    }
    //&#26657;&#39564;&#24212;&#29992;&#26159;&#21542;&#34987;&#25480;&#20104;&#26435;&#38480;
    try{
      grantStatus = await atManager.checkAccessToken(tokenId,permission);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`)
    }
    return grantStatus;

  }
  //定义参数mapOption,设置地图中心点坐标以及层级。
  private mapOption?: mapCommon.MapOptions;
  //定义参数callback,通过callback回调的方式获取MapComponentController对象,用来操作地图。
  private callback?: AsyncCallback<map.MapComponentController>
  //定义TAG
  private TAG = 'HuaweiMyLocationDemo';
  //地定义地图参数mapController,获取地图的控制器类,用来操作地图
  private mapController?: map.MapComponentController;
  aboutToAppear(): void {
    this.checkPermission();
    // 地图初始化参数,设置地图中心坐标以及层级
    this.mapOption = {
      position: {
        target: {
          latitude: 39.9,
          longitude:116.4
        },
        zoom: 10
      },
      myLocationControlsEnabled: true,
      scaleControlsEnabled: true,
    };
    // 地图初始化的回调
    this.callback = async (err, mapController) => {
      if(!err) {
        //获取地图的控制器类,用来操作地图
        this.mapController = mapController;
        // 启用我的位置图层
        this.mapController?.setMyLocationEnabled(true);
        //启用我的位置按钮。
        this.mapController?.setMyLocationControlsEnabled(true);
        this.mapController.setZoomControlsEnabled(true);
        // &#25351;&#21335;&#38024;&#24320;&#20851;
        this.mapController.setCompassControlsEnabled(true);
        //&#28378;&#21160;&#30456;&#26426;&#65292;&#23558;&#30456;&#26426;&#25353;&#29031;&#25351;&#23450;&#30340;&#20687;&#32032;&#28857;&#31227;&#21160;
        let x = 100.0;
        let y = 100.0;
        let cameraUpdate = map.scrollBy(x, y);
        // &#20197;&#21160;&#30011;&#26041;&#24335;&#31227;&#21160;&#22320;&#22270;&#30456;&#26426;
        this.mapController.animateCamera(cameraUpdate, 1000);
        // &#35774;&#32622;&#26368;&#23567;&#20559;&#22909;&#32553;&#25918;&#32423;&#21035;&#65292;&#33539;&#22260;&#20026;[2,20]
        this.mapController.setMinZoom(6);
        // &#35774;&#32622;&#26368;&#22823;&#20559;&#22909;&#32553;&#25918;&#32423;&#21035;&#65292;&#33539;&#22260;&#20026;[2,20]
        this.mapController.setMaxZoom(14);
        let style: mapCommon.MyLocationStyle = {
          anchorU: 0.5,
          anchorV: 0.5,
          radiusFillColor: 0xffff0000,
          // icon&#20026;&#33258;&#23450;&#20041;&#22270;&#26631;&#36164;&#28304;&#65292;&#20351;&#29992;&#26102;&#38656;&#35201;&#26367;&#25442;
          // &#22270;&#26631;&#23384;&#25918;&#22312;resources/rawfile&#65292;icon&#21442;&#25968;&#20256;&#20837;rawfile&#25991;&#20214;&#22841;&#19979;&#30340;&#30456;&#23545;&#36335;&#24452;
          icon: 'icon.png',
        };
        await this.mapController.setMyLocationStyle(style);
        //&#21021;&#22987;&#21270;&#25105;&#30340;&#20301;&#32622;
        this.getMyLocation()
      }
    }

  }
  build() {
    Stack() {
      MapComponent({mapOptions: this.mapOption, mapCallback: this.callback}).width('100%').height('100%');
    }.height('100%')
  }
  // 获取当前位置并视图移动过去
  getMyLocation() {
    geoLocationManager.getCurrentLocation().then(async (result) => {
      console.log('MapSignIn', 'getMyLocation = ' + JSON.stringify(result))
      let position: geoLocationManager.Location = {
        "latitude": result.latitude,
        "longitude": result.longitude,
        "altitude": 0,
        "accuracy": 0,
        "speed": 0,
        "timeStamp": 0,
        "direction": 0,
        "timeSinceBoot": 0
      };
      this.mapController?.setMyLocation(position)
      //创建CameraUpdate对象
      let gcj02Position: mapCommon.LatLng = await this.convertCoordinate(result.latitude,result.longitude)
      let latLng: mapCommon.LatLng = {
        latitude: gcj02Position.latitude,
        longitude:gcj02Position.longitude
      }
      let zoom = 14;
      let cameraUpdate = map.newLatLng(latLng,zoom)
      // 以动画方式移动地图相机
      this.mapController?.animateCamera(cameraUpdate,1000);
    })
  }
  async convertCoordinate(latitude: number, longitude: number): Promise<mapCommon.LatLng> {
    let wgs84Position: mapCommon.LatLng = {
      latitude: latitude,
      longitude: longitude
    }
    let gcj02Postion: mapCommon.LatLng = await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02,wgs84Position);
    return gcj02Postion;
  }
}
分享
微博
QQ
微信
回复
9天前
相关问题
HarmonyOS 应用图标显示
138浏览 • 1回复 待解决
HarmonyOS shortcuts图标显示异常
83浏览 • 1回复 待解决
HarmonyOS 偶现app图标显示错误
186浏览 • 1回复 待解决
HarmonyOS tabs位置如何居左显示
87浏览 • 1回复 待解决
HarmonyOS heif图片无法显示
117浏览 • 1回复 待解决
HarmonyOS stack子view无法自由调位置
85浏览 • 1回复 待解决