HarmonyOS地图标记和定位怎么使用

生活服务模块需要使用地图,定位,以及标记地点有没有现成的指导和代码参考。

HarmonyOS
2024-09-10 11:26:55
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang

请参考以下代码。地图标记的案例代码:

import { AsyncCallback } from '@kit.BasicServicesKit'; 
@Entry 
@Component 
struct MarkerDemo { 
  private mapOptions?: mapCommon.MapOptions; 
  private mapController?: map.MapComponentController; 
  private callback?: AsyncCallback<map.MapComponentController> 
  private marker?: map.Marker; 
  aboutToAppear(): void { 
    // 地图初始化参数 
    this.mapOptions = { 
      position: { 
        target: { 
          latitude:31.984410259206815, 
          longitude: 118.76625379397866 
        }, 
        zoom: 15 
      } 
    }; 
    this.callback = async (err, mapController) => { 
      if(!err) { 
        this.mapController = mapController; 
        //Marker初始化参数 
        let markerOptions: mapCommon.MarkerOptions = { 
          position: { 
            latitude: 31.984410259206815, 
            longitude: 118.76625379397866 
          }, 
          /*rotation: 0, 
          visible: true, 
          zIndex: 0, 
          alpha: 1, 
          anchorU: 0.5, 
          anchorV: 1, 
          clickable: true, 
          draggable: true, 
          flat: false,*/ 
          // 图标存放在resources/rawfile,icon参数传入rawfile文件夹下的相对路径 
          //icon: 'icon.png' 
        }; 
        //创建Marker 
        this.marker = await this.mapController.addMarker(markerOptions); 
        //设置信息窗的标题 
        this.marker.setTitle('南京'); 
        // 设置信息窗的子标题 
        this.marker.setSnippet('华东地区') 
        // 设置信息窗的锚点位置 
        this.marker.setInfoWindowAnchor(1,1) 
        // 设置信息窗可见 
        this.marker.setInfoWindowVisible(true) 
        //设置标记可拖拽 
        this.marker.setDraggable(true) 
        //设置标记锚点 
        this.mapController.on("markerDragStart", (marker) => { 
          console.info(`on-markerDragStart position = ${JSON.stringify(marker)}`); 
        }) 
        // 监听标记拖拽事件 
        this.mapController.on("markerDrag", (marker) => { 
          console.info(`on-markerDrag position = ${JSON.stringify(marker)}`) 
        }) 
        //设置监听标记拖动事件 
        this.mapController.on("markerClick", (marker) => { 
          console.info(`on-markerClick position = ${JSON.stringify(marker)}`) 
        }) 
        // 构造RotateAnimation对象 
        let animation = new map.RotateAnimation(0,360); 
        // 动画执行时间 
        animation.setDuration(2000); 
        //动画结束状态 
        animation.setFillMode(map.AnimationFillMode.BACKWARDS) 
        // 动画重复模式 
        animation.setRepeatMode(map.AnimationRepeatMode.REVERSE) 
        // 动画重复次数 
        animation.setRepeatCount(1) 
        // 根据开发需要设置动画监听 
        animation.on("start", () => { 
          console.info('start RotateAnimation') 
        }) 
        animation.on("end", () => { 
          console.info('end RotateAnimation'); 
        }) 
        // 设置动画 
        this.marker.setAnimation(animation); 
        // 开启动画 
        this.marker.startAnimation(); 
      } 
    } 
  } 
  build() { 
    Stack() { 
      Column() { 
        MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback}); 
      }.width('100%') 
    }.height('100%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.

地图定位”的案例代码:

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; 
        //开启3d建筑图层 
        let cameraUpdate = map.zoomTo(18); 
        this.mapController?.moveCamera(cameraUpdate); 
        this.mapController?.setBuildingEnabled(true); 
        // 启用我的位置图层 
        this.mapController?.setMyLocationEnabled(true); 
        //启用我的位置按钮 
        this.mapController?.setMyLocationControlsEnabled(true); 
        let style: mapCommon.MyLocationStyle = { 
          anchorU: 0.5, 
          anchorV: 0.5,radiusFillColor: 0xffff0000, 
          // icon为自定义图标资源,使用时需要替换 
          // 图标存放在resources/rawfile,icon参数传入rawfile文件夹下的相对路径 
          icon: 'icon.png', 
          //displayType: mapCommon.MyLocationDisplayType.FOLLOW 
        }; 
        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 = 17; 
      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; 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
分享
微博
QQ
微信
回复
2024-09-10 17:34:18
相关问题
HarmonyOS 地图定位介绍
1039浏览 • 1回复 待解决
HarmonyOS 定位地图是否有推荐的SDK?
1050浏览 • 1回复 待解决
HarmonyOS 定位服务、地图服务
724浏览 • 1回复 待解决
HarmonyOS 怎么进行图标图片适配
592浏览 • 1回复 待解决
HarmonyOS 地图组件里marker固定位
688浏览 • 1回复 待解决
地图定位不准,是什么原因啊?
857浏览 • 1回复 待解决
HarmonyOS地图使用问题
988浏览 • 1回复 待解决