参考DEMO:import { map, mapCommon, MapComponent } from '@kit.MapKit' import { AsyncCallback } from '@kit.BasicServicesKit' @Entry @Component export struct Test { private mapOption?: mapCommon.MapOptions; private mapController?: map.MapComponentController; private callback?: AsyncCallback<map.MapComponentController>; private markers: map.Marker[] = [] private nums: string = '' aboutToAppear(): void { this.mapOption = { position: { target: { latitude: 32.120750, longitude: 118.788765 }, zoom: 15 } } // 地图初始化的回调 this.callback = async (err, mapController) => { if (!err) { // 获取地图的控制器类,用来操作地图 this.mapController?.setMyLocationEnabled(true) this.mapController?.setMyLocationControlsEnabled(true) this.mapController = mapController; this.mapController.on("mapClick", (position) => { console.info("mapClick", `on-mapClick position = ${position.longitude}`); }); this.mapController.on("markerClick", (marker) => { console.info(`on-markerClick position = ${JSON.stringify(marker)}`) marker.setInfoWindowVisible(true); }); } } } async setMarkerWithHotels() { // this.mapController?.clear() for (let i = 0; i < 10; i++) { let markerOptions: mapCommon.MarkerOptions = { position: { latitude: 32.120750 + i * 0.01, longitude: 118.788765 + i * 0.01 }, rotation: 0, title: String(i), visible: true, zIndex: 0, alpha: 1, anchorU: 0.5, anchorV: 1, clickable: true, draggable: false, flat: false, icon: $r("app.media.startIcon") }; console.log(`markerOptions+${JSON.stringify(markerOptions)}`) // 新建marker let marker = await this.mapController?.addMarker(markerOptions); console.log(`marker+${JSON.stringify(marker)}`) if (marker) { this.markers.push(marker) console.log(`marker+${JSON.stringify(this.markers.push(marker))}`) } } } build() { NavDestination() { Stack() { Column() { MapComponent({ mapOptions: this.mapOption, mapCallback: this.callback, // 自定义信息窗 customInfoWindow: this.customInfoWindow }) .width('100%') .height('100%'); }.width('100%') Button() { Text('setMarkerWithHotels') }.onClick(() => { this.setMarkerWithHotels() }) }.height('100%') } } // 自定义信息窗BuilderParam @BuilderParam customInfoWindow: ($$: map.MarkerDelegate) => void = this.customInfoWindowBuilder; // 自定义信息窗Builder @Builder customInfoWindowBuilder($$: map.MarkerDelegate) { if ($$.marker) { Text($$.marker.getTitle()) .width("50%") .height(50) .backgroundColor(Color.Green) .textAlign(TextAlign.Center) .fontColor(Color.Black) .font({ size: 25, weight: 10, style: FontStyle.Italic }) .border({ width: 3, color: Color.Black, radius: 25, style: BorderStyle.Dashed }) } } }
参考DEMO: