地图标记的案例代码: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%') } }“地图定位”的案例代码: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; } }
地图标记的案例代码:
“地图定位”的案例代码: