DEV Community

HarmonyOS
HarmonyOS

Posted on

How to add polylines to a map, change polyline color, and set polyline texture

Read the original article:How to add polylines to a map, change polyline color, and set polyline texture

Problem description

How to add a polyline on a map, change its color, and set its texture?

Background knowledge

1- Use the addPolyline interface to add a polyline .

2- Use the setColor interface to set the color value of the polyline.

3- Use the customTexture property of MapPolylineOptions to set the polyline texture

Solution

1- Use the addPolyline interface to add a polyline . The line is black by default.

2- Use the setColor interface to set the color value of the polyline.

3- Use the customTexture property of MapPolylineOptions to set the polyline texture. This property supports two formats: ResourceStr and image.PixelMap. It is recommended to use an image without a background color (transparent color) for the texture.

Code example:

import { map, mapCommon, MapComponent } from '@kit.MapKit';
import { AsyncCallback } from '@kit.BasicServicesKit';

@Entry
@Component
struct MapPolylineDemo {
  private mapOptions?: mapCommon.MapOptions;
  private mapController?: map.MapComponentController;
  private callback?: AsyncCallback<map.MapComponentController>;
  private mapPolyline?: map.MapPolyline;

  aboutToAppear(): void {
    // Map initialization parameters
    this.mapOptions = {
      position: {
        target: {
          latitude: // ...,
          longitude: // ...
        },
        zoom: 14
      }
    };
    this.callback = async (err, mapController) => {
      if (!err) {
        this.mapController = mapController;

        // polyline initialization parameters
        let polylineOption: mapCommon.MapPolylineOptions = {
          points: [
            {
              longitude: // ...,
              latitude: // ...
            },
            {
              longitude: // ...,
              latitude: // ...
            },
            {
              longitude: // ...,
              latitude: // ...
            }
          ],
          // The color of the line. The default value is 0xff000000 (black).
          color: 0xffed6f21,
          // The width of the polyline, unit: px, the default value is 10
          width: 50,
          // Polyline texture. It is recommended to use an image with no background color (transparent color) for the texture.
          customTexture: $r("app.media.test"),
        }
        // Create polyline
        this.mapPolyline = await this.mapController.addPolyline(polylineOption);
      }
    };
  }

  build() {
    Stack() {
      Column() {
        MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
      }.width('100%')
    }.height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Written by Merve Yonetci

Top comments (0)