问题代码示例如下:
@Entry @Component struct MarkerPage { aboutToAppear(): void { this.mapOptions = { position: { target: { latitude: 31.984410259206815, longitude: 118.76625379397866 }, zoom: 10 }, myLocationControlsEnabled: true }; this.callback = async (err, mapController) => { if (!err) { this.mapController = mapController; this.mapEventManager = this.mapController.getEventManager(); mapController.setMyLocationEnabled(true); mapController.setMyLocationControlsEnabled(true) let callback = () => { } this.mapEventManager.on("mapLoad", callback); } }; } build() { NavDestination() { Stack() { MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback }) } } .onReady(async (context) => { if (context) { this.pathStack = context.pathStack let position: mapCommon.LatLng = { latitude: 31.984410259206815, longitude: 118.76625379397866 }; let markerOptions: mapCommon.MarkerOptions = { position: position }; this.marker = await this.mapController?.addMarker(markerOptions) } }) } }
将this.marker = await this.mapController?.addMarker(markerOptions)相关的代码挪到Mapkit的callback方法里执行,代码示例如下:
import { MapComponent, mapCommon, map } from '@kit.MapKit'; import { AsyncCallback } from '@kit.BasicServicesKit'; @Entry @Component struct MarkerPage { private mapOptions?: mapCommon.MapOptions; private callback?: AsyncCallback<map.MapComponentController>; private mapController?: map.MapComponentController; private mapEventManager?: map.MapEventManager; pathStack: NavPathStack = new NavPathStack(); aboutToAppear(): void { this.mapOptions = { position: { target: { latitude: 31.984410259206815, longitude: 118.76625379397866 }, zoom: 10 }, myLocationControlsEnabled: true }; // 地图初始化的回调 this.callback = async (err, mapController) => { if (!err) { // 获取地图的控制器类,用来操作地图 this.mapController = mapController; this.mapEventManager = this.mapController.getEventManager(); mapController.setMyLocationEnabled(true); mapController.setMyLocationControlsEnabled(true); let callback = () => { }; this.mapEventManager.on('mapLoad', callback); let position: mapCommon.LatLng = { latitude: 31.984410259206815, longitude: 118.76625379397866 }; let markerOptions: mapCommon.MarkerOptions = { position: position }; try { await this.mapController?.addMarker(markerOptions); } catch (error) { console.error('addMarker error'); } } }; } build() { NavDestination() { Stack() { // 调用MapComponent组件初始化地图 MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback }) .width('100%') .height('75%'); } .height('100%'); } .hideTitleBar(true) .onReady(async (context) => { if (context) { this.pathStack = context.pathStack; } }) .onShown(() => { if (this.mapController) { this.mapController.show(); } }) .onHidden(() => { if (this.mapController) { this.mapController.hide(); } }); } }