import { MapComponent, mapCommon, map } from '@kit.MapKit'; import { AsyncCallback } from '@kit.BasicServicesKit'; import { geoLocationManager } from '@kit.LocationKit';
@Component struct Location { mapCallback?: AsyncCallback<map.MapComponentController> controller?: map.MapComponentController @Consume currentMessage: string
// 这里属于业务:变化的内容,以后这里根据业务来微调 async getLocation() { // 需要切换真实的4个在AGC配置的证书 //1.geoLocationManager获取当前经纬度的坐标 const result = await geoLocationManager.getCurrentLocation() //2.经纬度转化成街道 const res = await geoLocationManager.getAddressesFromLocation({ latitude: result.latitude, longitude: result.longitude }) this.currentMessage = res[0].placeName as string //3.设置当前位置 点击进去配置项有很多是必填的 this.controller?.setMyLocation({ latitude: result.latitude, longitude: result.longitude, accuracy: 0, altitude: 0, speed: 0, timeStamp: 0, direction: 0, timeSinceBoot: 0, altitudeAccuracy: 0, speedAccuracy: 0, directionAccuracy: 0, uncertaintyOfTimeSinceBoot: 0, sourceType: 1 }) //4.准备一个相机,位置挪到定位处 let cameraUpdate: map.CameraUpdate = map.newCameraPosition({ target: { longitude: result.longitude, latitude: result.latitude }, zoom: 16 }) this.controller?.moveCamera(cameraUpdate) // 中国大陆香港澳门使用***GCJ02坐标,若使用WGS84坐标直接放在华为地图上,会有偏差。 // 所以在国内需要先把WGS84坐标转换成GCJ02坐标,再使用。 // 坐标转换: 花瓣地图的wgs84 转换成-> gcj02 // 自己绘制的有偏差,所以需要使用花瓣地图的转换方法 const newPostion: mapCommon.LatLng = await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, result) //5.自定义打点展示 // 当前定位的坐标的自定义标识marker this.controller?.addMarker({ position: { latitude: newPostion.latitude, longitude: newPostion.longitude }, //提示文字 title: '当前位置:', snippet: this.currentMessage, clickable: true }) // 有效区域-圆形当前位置的阴影设置 this.controller?.addCircle({ // 半径距离 radius: 500, // 圆的中心位置 center: { latitude: newPostion.latitude, longitude: newPostion.longitude }, // 圆的颜色,前面是0X透明度 fillColor: 0XFF00FF0F }) // 展示当前定位的街道信息 // 线路绘制... }
aboutToAppear(): void { //err, controller中,参数controller控制地图的 this.mapCallback = async (err, controller) => { if (!err) { this.controller = controller // 设置地图展示位置 this.controller.setMyLocationEnabled(true) // 设置地图的控制器 this.controller.setMyLocationControlsEnabled(true) // 开启3d建筑模式 this.controller.setBuildingEnabled(true); // 设置地图具体位置 this.getLocation() } }
}
build() { // 地图组件 MapComponent({ mapOptions: { // 当前定位的坐标 position: { target: { latitude: 123.1531, longitude: 123.1531 }, // 缩放层级 zoom: 16 } }, 地图初始化后的回调函数 mapCallback: this.mapCallback }) .width('100%') .height('100%') } }
export default Location