HarmonyOS 设置我的位置功能后并未显示当前位置点,需要点击定位才能显示当前定位点

HarmonyOS  设置我的位置功能后并未显示当前位置点,需要点击定位才能显示当前定位点

HarmonyOS
2024-08-14 16:07:17
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

可以参考以下代码:

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; 
 
    //获取应用程序的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}`) 
    } 
    //校验应用是否被授予权限 
    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); 
        // 指南针开关 
        this.mapController.setCompassControlsEnabled(true); 
        //滚动相机,将相机按照指定的像素点移动 
        let x = 100.0; 
        let y = 100.0; 
        let cameraUpdate = map.scrollBy(x, y); 
        // 以动画方式移动地图相机 
        this.mapController.animateCamera(cameraUpdate, 1000); 
        // 设置最小偏好缩放级别,范围为[2,20] 
        this.mapController.setMinZoom(6); 
        // 设置最大偏好缩放级别,范围为[2,20] 
        this.mapController.setMaxZoom(14); 
        let style: mapCommon.MyLocationStyle = { 
          anchorU: 0.5, 
          anchorV: 0.5, 
          radiusFillColor: 0xffff0000, 
          // icon为自定义图标资源,使用时需要替换 
          // 图标存放在resources/rawfile,icon参数传入rawfile文件夹下的相对路径 
          icon: 'icon.png', 
        }; 
        await this.mapController.setMyLocationStyle(style); 
        //初始化我的位置 
        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
微信
回复
2024-08-14 21:00:26
相关问题
求告知如何获取当前定位
325浏览 • 1回复 待解决
定位是否必须联网才能成功?
1642浏览 • 1回复 待解决