打开页面时,可以定位到当前的位置,但是不显示我的位置标志图片。
代码如下:
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%")
}
}
可以参考如下demo示例