目录

Displaying a Map

Use Cases

Starting from 5.0.3(15), the logo scaling and 3D globe view functions are supported. Starting from 5.1.1(19), the indoor map and scale unit setting functions are supported. Starting from 6.0.0(20), the map language setting function is supported. Starting from 6.1.0(23), the function of setting city lighting effect for the 3D globe view is supported. Starting from 26.0.0, the function of replacing the 3D globe view background is supported.

This section describes how to use the map components MapComponent and MapComponentController to display a map, as shown in the following figure.

API Description

The map display function is mainly provided by MapComponent. For more information about the APIs, please refer to API Reference.

API Description
mapCommon.MapOptions Sets initialization attributes of a map component.
MapComponent(mapOptions: mapCommon.MapOptions, mapCallback: AsyncCallback<map.MapComponentController>) Map component.
map.MapComponentController Main entry class for map operations. It provides access for all map-related methods. It provides the following functions: switching the map type (such as standard map and empty map), changing the map status (coordinates of the map center point and zoom level), adding Markers, drawing geometric shapes (including MapPolyline, MapPolygon, and MapCircle), and listening for various events.

Development Procedure

[h2]Map Display

  1. Import required modules of Map Kit.

    import { MapComponent, mapCommon, map } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';
  2. Create the map initialization parameter mapOptions and set the coordinates of the map center point and zoom level.

    Obtain a MapComponentController object in callback mode to operate the map.

    Call the MapComponent component and pass the mapOptions and mapCallback parameters to initialize the map.

    @Entry
    @Component
    struct MapPresentingDemo {
      // ...
      private TAG = 'MapPresentingDemo';
      private mapOptions?: mapCommon.MapOptions;
      private callback?: AsyncCallback<map.MapComponentController>;
      private mapController?: map.MapComponentController;
      private mapEventManager?: map.MapEventManager;
    
      aboutToAppear(): void {
        // Map initialization parameters used to set the coordinates of the map center point and zoom level.
        this.mapOptions = {
          position: {
            target: {
              latitude: 39.9,
              longitude: 116.4
            },
            zoom: 10
          }
        };
    
        // Map initialization callback.
        this.callback = async (err, mapController) => {
          if (!err) {
            // Obtain the controller class of the map to operate the map.
            this.mapController = mapController;
            this.mapEventManager = this.mapController.getEventManager();
            let callback = () => {
              console.info(this.TAG, `on-mapLoad`);
            }
            this.mapEventManager.on('mapLoad', callback);
          } else {
            console.error(`Failed to initialize the map. Code: ${err.code}; message: ${err.message}`);
          }
        };
      }
    
      // This is called each time the page is displayed, for example, during page redirection or when the app is switched to the foreground. It works only for the custom components decorated using @Entry.
      onPageShow(): void {
        // You are advised to call the show method of the map component to switch to the foreground.
        if (this.mapController) {
          this.mapController.show();
        }
      }
    
      // This is called each time the page is hidden, for example, during page redirection or when the app is switched to the background. It works only for the custom components decorated using @Entry.
      onPageHide(): void {
        // You are advised to call the hide method of the map component to switch to the background.
        if (this.mapController) {
          this.mapController.hide();
        }
      }
    
      build() {
        // ...
          Stack() {
            // Call the MapComponent component to initialize the map.
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback }).width('100%').height('100%');
          }
    
          // ...
      }
    }
  3. Run the project, and you can view the map in your app, as shown in the screenshot below.

    If the map fails to be loaded, see Map Not Displayed.

[h2]Setting Map Attributes

The following table describes attributes of MapOptions.

Attribute Description
mapType Map type. The default value is MapType.STANDARD.
position Map camera position.
bounds Map display box.
minZoom Minimum zoom level of a map, which ranges from 2 to 20. The default value is 2.
maxZoom Maximum zoom level of a map, which ranges from 2 to 20. The default value is 20.
rotateGesturesEnabled Indicates whether to support rotate gestures. The default value is true.
scrollGesturesEnabled Indicates whether to support scroll gestures. The default value is true.
zoomGesturesEnabled Indicates whether to support zoom gestures. The default value is true.
tiltGesturesEnabled Indicates whether to support tilt gestures. The default value is true.
zoomControlsEnabled Indicates whether to display the zoom control. The default value is true.
myLocationControlsEnabled Indicates whether to display the my-location icon. The default value is false.
compassControlsEnabled Indicates whether to display the compass control. The default value is true.
scaleControlsEnabled Indicates whether to display the scale control. The default value is false.
alwaysShowScaleEnabled Indicates whether to always display the scale control. The default value is false.
padding Padding between the map and edges.
styleId Custom style ID.
dayNightMode Day/Dark mode. The default value is DayNightMode.DAY (day mode).
logoScale Logo scaling ratio. The value range is [0.8, 1]. The default value is 1.
sphereEnabled Indicates whether to enable the 3D globe view. The default value is false.
indoorMapEnabled Indicates whether to enable the indoor map. The default value is false.
scaleUnit Map scale unit, metric or imperial. The default value is ScaleUnit.METRIC_UNIT (metric unit).
  1. Set mapType. For details, please refer to Changing the Map Type.

  2. Set myLocationControlsEnabled to display the my-location icon.

    Set myLocationControlsEnabled to true in mapOptions to display the my-location icon . The following shows a configuration example.

    You can also call the method of the MapComponentController object to display the my-location icon. For details, please refer to Showing My Location.

    this.mapOptions = {
      position: {
        target: {
          latitude: 39.9,
          longitude: 116.4
        },
        zoom: 10
      },
      myLocationControlsEnabled: true
    };

  3. Display the scale.

    Set scaleControlsEnabled to true in mapOptions to display the scale. The following shows a configuration example.

    this.mapOptions = {
      position: {
        target: {
          latitude: 39.9,
          longitude: 116.4
        },
        zoom: 10
      },
      scaleControlsEnabled: true
    };

[h2]Enabling the BuildingOverlay

Call the setBuildingEnabled method of the MapComponentController object to enable the BuildingOverlay. Users can zoom in on the map to level 16 or above, and use two fingers to swipe upward on the screen to tilt the map to view the BuildingOverlay effect.

this.mapController.setBuildingEnabled(true);

The following figure illustrates the effects.

[h2]Switching Between the Map Foreground and Background

You can use the MapComponentController object to manage the lifecycle of a map page switching between foreground and background. When an app triggers a switchover between the foreground and background on a map page, the show/hide function can be called in the page lifecycle to apply for or release resources.

Switch the map to the foreground:

// This is called each time the page is displayed, for example, during page redirection or when the app is switched to the foreground. It works only for the custom components decorated using @Entry.
onPageShow(): void {
  // You are advised to call the show method of the map component to switch to the foreground.
  if (this.mapController) {
    this.mapController.show();
  }
}

Switch the map to the background:

// This is called each time the page is hidden, for example, during page redirection or when the app is switched to the background. It works only for the custom components decorated using @Entry.
onPageHide(): void {
  // You are advised to call the hide method of the map component to switch to the background.
  if (this.mapController) {
    this.mapController.hide();
  }
}

[h2]Dark Mode

Map Kit provides two methods to set the dark mode of a map: during map initialization and after map creation.

Method 1: During map initialization

Set the dayNightMode parameter in the map initialization parameters. The options are DAY (day mode), NIGHT (dark mode), and AUTO (automatic mode). If dayNightMode is set to AUTO, the map's dark mode will follow the system. If the system has enabled the dark mode, the map uses the dark mode. Otherwise, the map uses the day mode.

this.mapOptions = {
  position: {
    target: {
      latitude: 39.9,
      longitude: 116.4
    },
    zoom: 10
  },
  myLocationControlsEnabled: true,
  // Set the map to the dark mode.
  dayNightMode: mapCommon.DayNightMode.NIGHT
};

Method 2: After map creation

After the map is created, call the setDayNightMode method of the MapComponentController object to set the dark mode. Set the parameter in the following example to AUTO, and enable the dark mode of the system. Then the map automatically changes to the dark mode.

// Set the map to the auto mode.
this.mapController.setDayNightMode(mapCommon.DayNightMode.AUTO);

[h2]Indoor Map

The indoor map allows users to view floor plans to check the interior layout of places such as shopping malls, museums, and hospitals.

Map Kit provides two methods to enable the indoor map: during map initialization and after map creation.

Method 1: During map initialization

During map initialization, set indoorMapEnabled to true in the initialization parameter MapOptions. The indoor map and the floor selector control are only visible at map zoom level 17 and above. Users can switch between different indoor map floors using the floor selector control in the lower left corner.

this.mapOptions = {
  position: {
    target: {
      latitude: 31.979227,
      longitude: 118.762245
    },
    zoom: 18
  },
  // Enable the indoor map.
  indoorMapEnabled: true
};

Method 2: After map creation

After the map is created, call the setIndoorMapEnabled method of the MapComponentController object to enable the indoor map. In the following example, after the indoor map is enabled, the isIndoorMapEnabled method is called to check whether the indoor map is enabled, and the setFloorControlsPosition method is called to set the position of the floor selector control. The switchIndoorMapFloor method is also provided to switch to a specified indoor building and floor.

// Enable the indoor map.
this.mapController.setIndoorMapEnabled(true);
// Check whether the indoor map is enabled.
let isIndoorMapEnabled: boolean = this.mapController.isIndoorMapEnabled();
console.info('indoorMapEnabled is:' + isIndoorMapEnabled);
// Set the position of the floor selector control.
this.mapController.setFloorControlsPosition({
  positionX: 500,
  positionY: 500
});
// Switch to a specified floor. Replace the first input parameter with the required building ID and the second with the floor, for example, 1F or B1.
this.mapController.switchIndoorMapFloor('822588304363886720', '3F');

You can call the on('indoorMapEnter') method to listen for indoor map access events and the on('indoorMapExit') method to listen for indoor map exit events.

let callbackEnter = (indoorMapInfo: map.IndoorMapInfo) => {
  console.info(this.TAG, `on-indoorMapEnter`);
};
let callbackExit = () => {
  console.info(this.TAG, `on-indoorMapExit`);
};
// Callback of listening for indoor map access events.
this.mapEventManager.on('indoorMapEnter', callbackEnter);
// Callback of listening for indoor map exit events.
this.mapEventManager.on('indoorMapExit', callbackExit);

[h2]Setting the Logo Scaling Ratio

Map Kit provides two methods to set the logo scaling ratio of a map: during map initialization and after map creation.

Method 1: During map initialization

Set the logoScale parameter in the map initialization parameters. The value range is [0.8, 1], and the default value is 1.

// Method 1: During map initialization
this.mapOptions = {
  position: {
    target: {
      latitude: 39.9,
      longitude: 116.4
    },
    zoom: 10
  },
  myLocationControlsEnabled: true,
  // Set the logo scaling ratio to 0.9.
  logoScale: 0.9
};

Method 2: After map creation

  1. After the map is created, call the setLogoScale method of the MapComponentController object to set the logo scaling ratio.

    // Set the logo scaling ratio to 0.9.
    this.mapController.setLogoScale(0.9);
  2. Obtain the logo scaling ratio.

    Call the getLogoScale method of the MapComponentController object to obtain the current logo scaling ratio.

    // Obtain the logo scaling ratio.
    let logoScale: number = this.mapController.getLogoScale();

[h2]Enabling the 3D Globe View

Map Kit provides two methods to enable the 3D globe view: during map initialization and after map creation.

After the 3D globe view is enabled, users can clearly view the 3D globe when the zoom level is less than 4.

Method 1: During map initialization

Set the parameter indicating whether to enable the 3D globe view to true in the map initialization parameters. The default value is false.

// Method 1: During map initialization
this.mapOptions = {
  position: {
    target: {
      latitude: 39.9,
      longitude: 116.4
    },
    zoom: 2
  },
  // Enable the 3D globe view.
  sphereEnabled: true
};

Method 2: After map creation

After the map is created, call the setSphereEnabled method of the MapComponentController object to enable the 3D globe view. You can call the isSphereEnabled method of the MapComponentController object to check whether the 3D globe view is enabled.

// Enable the 3D globe view.
this.mapController.setSphereEnabled(true);
// Check whether the 3D globe view is enabled.
let result: boolean = this.mapController.isSphereEnabled();

The following figure illustrates the effects.

[h2]Enabling the City Lighting Effect

Call the setSphereEnabled(enabled: boolean, animateDuration: number, cityLight: boolean) method of the MapComponentController object to enable the city lighting effect.

[h2]Replacing the 3D Globe View Background

Replacing the 3D globe view background can be used to display global flight routes, cross-border routes, and visualized international logistics routes from the real perspective of the Earth.

let mSphereOptions: mapCommon.SphereParams =
  {
    // Enable the sunlight effect for the sphere.
    sunLightEnabled: true,
    // Enable the city light effect for the sphere.
    cityLightEnabled: true,
    // Set the animation duration to 1000 ms.
    animateDuration: 1000,
    // The image must be stored in the resources/base/media directory.
    backgroundImage: $r('app.media.bg_compress'),
    coverageImage: $r('app.media.coverage_icon')
  };
await this.mapController.setSphereMapEnabled(true, mSphereOptions);