目录

地图服务覆盖物image如何添加网络图片url

问题现象

Map Kit地图服务开发需要添加覆盖物,ImageOverlayParams参数中image只支持ResourceStr和image.PixelMap两种格式,如何将网络图片url添加到image中?

背景知识

解决方案

ImageOverlayParams类中image参数只支持ResourceStr和image.PixelMap,无法直接添加网络图片url,可以把网络图片的url转换成PixelMap类型显示。

  1. 通过http的request下载网络图片资源,并把网络图片url下载的ArrayBuffer类型的图片转换为PixelMap类型数据。
    // 通过http的request方法从网络下载图片资源
    async getPicture() {
      // 请填写一个具体的网络图片地址
      http.createHttp().request('xx.xx.xx.xx.png',
        async (error: BusinessError, data: http.HttpResponse) => {
          if (error) {
            console.error('get network picture error:' + error.message);
            return;
          }
          if (200 === data.responseCode) {
            const imageData: ArrayBuffer = data.result as ArrayBuffer;
            // 通过ArrayBuffer创建图片源实例
            const imageSource: image.ImageSource = image.createImageSource(imageData);
            const options: image.InitializationOptions = {
              'alphaType': 0,
              'editable': false,
              'pixelFormat': 3,
              'scaleMode': 1,
              'size': { height: 50, width: 50 }
            };
            // 通过属性创建PixelMap
            this.imageMap = await imageSource.createPixelMap(options);
          }
        });
    }
  1. 将转换后的PixelMap图片添加到ImageOverlayParams的image参数中。
    Button('添加网络图片覆盖物').onClick(async () => {
      let imageOverlayParams: mapCommon.ImageOverlayParams = {
        // 覆盖物范围
        bounds: {
          southwest: { latitude: 32, longitude: 118 },
          northeast: { latitude: 32.4, longitude: 118.4 }
        },
        // 转换过后的PixelMap图片
        image: this.imageMap,
        transparency: 0.3,
        zIndex: 101,
        anchorU: 0.5,
        anchorV: 0.5,
        clickable: true,
        visible: true,
        bearing: 0
      };
      // 添加覆盖物
      await this.mapController?.addImageOverlay(imageOverlayParams);
    })

完整示例参考如下:

import { http } from '@kit.NetworkKit';
import { image } from '@kit.ImageKit';
import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { map, mapCommon, MapComponent } from '@kit.MapKit';

@Component
@Entry
struct Index {
  @State imageMap: image.PixelMap | Resource = $r('app.media.startIcon');
  private mapOptions?: mapCommon.MapOptions;
  private mapController?: map.MapComponentController;
  private callback?: AsyncCallback<map.MapComponentController>;
  private mapEventManager?: map.MapEventManager;

  // 通过http的request方法从网络下载图片资源
  async getPicture() {
    // 请填写一个具体的网络图片地址
    http.createHttp().request('xx.xx.xx.xx.png',
      async (error: BusinessError, data: http.HttpResponse) => {
        if (error) {
          console.error('get network picture error:' + error.message);
          return;
        }
        if (200 === data.responseCode) {
          const imageData: ArrayBuffer = data.result as ArrayBuffer;
          // 通过ArrayBuffer创建图片源实例
          const imageSource: image.ImageSource = image.createImageSource(imageData);
          const options: image.InitializationOptions = {
            'alphaType': 0,
            'editable': false,
            'pixelFormat': 3,
            'scaleMode': 1,
            'size': { height: 50, width: 50 }
          };
          // 通过属性创建PixelMap
          this.imageMap = await imageSource.createPixelMap(options);
        }
      });
  }


  async aboutToAppear() {
    // 设置地图属性模型
    this.mapOptions = {
      position: {
        target: {
          latitude: 32.2,
          longitude: 118.2
        },
        zoom: 10
      }
    };
    // 地图回调
    this.callback = async (err, mapController) => {
      if (!err) {
        this.mapController = mapController;
        this.mapEventManager = this.mapController.getEventManager();
        await this.getPicture();
      } else {
        console.error(`地图初始化失败, code is:${err.code}, message is ${err.message}`);
      }
    };
  }

  build() {
    Stack() {
      Column() {
        Button('添加网络图片覆盖物').onClick(async () => {
          let imageOverlayParams: mapCommon.ImageOverlayParams = {
            // 覆盖物范围
            bounds: {
              southwest: { latitude: 32, longitude: 118 },
              northeast: { latitude: 32.4, longitude: 118.4 }
            },
            // 转换过后的PixelMap图片
            image: this.imageMap,
            transparency: 0.3,
            zIndex: 101,
            anchorU: 0.5,
            anchorV: 0.5,
            clickable: true,
            visible: true,
            bearing: 0
          };
          // 添加覆盖物
          await this.mapController?.addImageOverlay(imageOverlayParams);
        })
        MapComponent({
          mapOptions: this.mapOptions,
          mapCallback: this.callback,
        })
          .width('100%')
          .height('90%');

      }.width('100%')
    }.height('100%')
  }
}

常见FAQ

Q:MapKit绘制中是否支持自定义覆盖物,比如图文覆盖和自定义排版?

A:当前地图覆盖物仅支持图片,不支持图文覆盖和自定义排版。