map

This topic introduces the map components. If multiple map components are displayed on the same page, different IDs are required. The map components are the native components in an app, which have the highest level of the hierarchy.

Note: For related API, see my.createMapContext(mapId).

Prerequisites

Before you begin, make sure you have understood the following prerequisites:

  • Do not use the map components in scroll-view.
  • The map components do not support CSS animation.
  • If the user zooms in or zooms out the map, reset the value of scale in the onRegionChange function before setting the latitude and longitude of the location. Otherwise, the map restores to the original size. See the following sample codes of regionchange for details.
  • The mini program does not support obtaining the latitude and longitude of the current map.

Sample codes

See the following sample codes of the map component:

copy
<view class="page">
  <view class="page-section">
    <view class="page-section-demo">
      <map
        id="map"
        longitude="{{longitude}}"
        latitude="{{latitude}}"
        scale="{{scale}}"
        controls="{{controls}}"
        onControlTap="controltap"
        markers="{{markers}}"
        onMarkerTap="markertap"
        polyline="{{polyline}}"
        polygon="{{polygon}}"
        circles="{{circles}}"
        onRegionChange="regionchange"
        onTap="tap"
        onCalloutTap="callouttap"
        include-points="{{includePoints}}"
        ground-overlays="{{ground-overlays}}">
      </map>
    </view>
  </view>
  <view class="page-section-btns">
    <view onTap="demoResetMap">reset</view>
    <view onTap="demoGetCenterLocation">get center location</view>
    <view onTap="demoMoveToLocation">move to location</view>
  </view>
  <view class="page-section-btns">
    <view onTap="demoMarkerAnimation">animation</view>
    <view onTap="demoMarkerLabel">label</view>
    <view onTap="demoMarkerCustomCallout">custom callout</view>
  </view>
  <view class="page-section-btns">
    <view onTap="demoMarkerAppendStr">text marker</view>
    <view onTap="demoShowRoute">show route</view>
  </view>
  <view class="page-section-btns">
    <view onTap="demoCompass">compass</view>
    <view onTap="demoGesture">gesture</view>
  </view>
  <view class="page-section-btns">
    <view onTap="demoPolyline">polyline</view>
    <view onTap="demoPolygon">polygon</view>
    <view onTap="demoCircle">circle</cview>
  </view>
  <view class="page-section-btns">
  </view>
</view>

copy
const markers = [{
  id: 0,
  latitude: 30.266786,
  longitude: 120.10675,
  width: 19,
  height: 31,
  iconPath: 'https://gw.alipayobjects.com/mdn/rms_dfc0fe/afts/img/A*x9yERpemTRsAAAAAAAAAAAAAARQnAQ',
  callout: {
    content: 'callout',
  },
}];

const animMarker = [{
  id: 1,
  latitude: 30.266786,
  longitude: 120.10675,
  width: 19,
  height: 31,

  iconPath: 'https://gw.alipayobjects.com/mdn/rms_dfc0fe/afts/img/A*x9yERpemTRsAAAAAAAAAAAAAARQnAQ',

  markerLevel: 2
}];

const labelMarker = [{
  id: 2,
  latitude: 30.266786,
  longitude: 120.10675,
  width: 19,
  height: 31,
  iconPath: 'https://gw.alipayobjects.com/mdn/rms_dfc0fe/afts/img/A*x9yERpemTRsAAAAAAAAAAAAAARQnAQ',
  label:{
    content:"Hello Label",
    color:"#00FF00",
    fontSize:14,
    borderRadius:3,
    bgColor:"#ffffff",
    padding:10,
  },
  markerLevel: 2
}];
const customCalloutMarker = [{
  id: 3,
  latitude: 30.266786,
  longitude: 120.10675,
  width: 19,
  height: 31,
  iconPath: 'https://gw.alipayobjects.com/mdn/rms_dfc0fe/afts/img/A*x9yERpemTRsAAAAAAAAAAAAAARQnAQ',
  "customCallout":{
    "type": 2,
    "descList": [{
      "desc": "Estimation",
      "descColor": "#333333"
    }, {
      "desc": "5mins",
      "descColor": "#108EE9"
    }, {
      "desc": "Arrive",
      "descColor": "#333333"
    }],
    "isShow": 1
  },
  markerLevel: 2
}];

const iconAppendStrMarker = [{
  id: 34,
  latitude: 30.266786,
  longitude: 120.10675,
  width: 19,
  height: 31,
  iconAppendStr:"iconAppendStr",
  markerLevel: 2
}];

var myTrafficEnabled = 0;
var myCompassEnabled = 0;
var myScaleEnabled = 0;
var myGestureEnabled = 0;

const longitude = 120.10675;
const latitude = 30.266786;
const includePoints = [{
  latitude: 30.266786,
  longitude: 120.10675,
}];

Page({
  data: {
    scale: 14,
    longitude,
    latitude,
    includePoints,
  },
  onReady() {
    // use my.createMapContext JSAPI to get the map context
    this.mapCtx = my.createMapContext('map');
  },
  demoResetMap() {
    this.setData({
      scale: 14,
      longitude,
      latitude,
      includePoints,
      'ground-overlays':[],
      circles:[],
      polygon:[],
      polyline:[],
    });
    this.mapCtx.clearRoute();
  },
  demoGetCenterLocation() {
    this.mapCtx.getCenterLocation({
      success: (res) => {
        my.alert({
          content: 'longitude:' + res.longitude + '\nlatitude:' + res.latitude + '\nscale:' + res.scale,
        });
        console.log(res.longitude);
        console.log(res.latitude);
        console.log(res.scale);
      },
    });
  },
  demoMoveToLocation() {
    this.mapCtx.moveToLocation();
  },
  demoMarkerAnimation() {
    
    this.mapCtx.updateComponents({
      'markers':animMarker,
    });
    this.mapCtx.updateComponents({
      command:{
        markerAnim:[{markerId:1,type:0},],
      }
    });
  },
  demoMarkerLabel() {
    
    this.mapCtx.updateComponents({
      scale: 14,
      longitude,
      latitude,
      includePoints,
      'markers':labelMarker,
    });
  },
  demoMarkerCustomCallout() {
    this.mapCtx.updateComponents({
      scale: 14,
      longitude,
      latitude,
      includePoints,
      'markers':customCalloutMarker,
    });
  },
  demoMarkerAppendStr() {
    this.mapCtx.updateComponents({
      scale: 14,
      longitude,
      latitude,
      includePoints,
      'markers':iconAppendStrMarker,
    });
  },
  demoShowRoute() {
    this.mapCtx.showRoute({
      startLat:30.257839, 
      startLng:120.062726,
      endLat:30.256718,
      endLng:120.059985,
      zIndex:4,
      routeColor:'#FFB90F',
      iconPath: "https://gw.alipayobjects.com/mdn/rms_dfc0fe/afts/img/A*EGCiTYQhBDkAAAAAAAAAAAAAARQnAQ",
      iconWidth:10,
      routeWidth:10
     });
  },
  demoCompass() {
    myCompassEnabled = (myCompassEnabled+1) %2;
    this.mapCtx.showsCompass({isShowsCompass:myCompassEnabled});
  },
  demoGesture() {
    myGestureEnabled = (myGestureEnabled+1) %2;
    this.mapCtx.gestureEnable({isGestureEnable:myGestureEnabled});
  },
  demoPolyline() {
    this.setData({
      scale: 16,
      longitude,
      latitude,
      polyline: [{
        points: [{// right-top
          latitude: 30.264786,
          longitude: 120.10775,
        },{// left-bottom
          latitude: 30.268786,
          longitude: 120.10575,
        }],
        color: '#FF0000DD',
        width: 10,
        dottedLine: false,
        iconWidth:10,
      }],
    });
  },
  demoPolygon() {
    this.setData({
      scale: 16,
      longitude,
      latitude,
      polygon: [{
        points: [{// right-top
          latitude: 30.264786,
          longitude: 120.10775,
        },{//   right-bottom
          latitude: 30.268786,
          longitude: 120.10775,
        },{//  left-bottom
          latitude: 30.268786,
          longitude: 120.10575,
        },{// left=top
          latitude: 30.264786,
          longitude: 120.10575,
        }],
        fillColor: '#BB0000DD',
        width: 5,
      }],
    });
    
  },
  demoCircle() {
    this.setData({
      scale: 16,
      longitude,
      latitude,
      circles: [{
        longitude,
        latitude,
        color: '#BB76FF88',
        fillColor: '#BB76FF33',
        radius: 100,
        strokeWidth:3,
    }]
    });
  },
  regionchange(e) {
    console.log('regionchange', e);
  },
  onPanelTap(e) {
    console.log('paneltap:', e);
  },
  markertap(e) {
    console.log('marker tap', e);
  },
  controltap(e) {
    console.log('control tap', e);
  },
  tap() {
    console.log('tap');
  },
  callouttap(e) {
    console.log('callout tap', e);
  },
});

Parameters

Property

Type

Description

id

String

The ID to identify the map component.

style

String

Inline style.

latitude

Number

The latitude of the central point.

longitude

Number

The longitude of the central point.

scale

Number

The zoom level. The value ranges from 5 to 18.

Default value: 16

skew

Number

The skew angle, range 0 ~ 40, specific to the zoom level.

Default value: 0

rotate

Number

The angle at which the map is rotated clockwise, ranging from 0 to 360 degrees.

Default value: 0

markers

Array

The location marker. See markers for details.

polyline

Array

The polyline. See polyline for details.

circles

Array

The circle. See circles for details.

controls

Array

The controls in the map view.

See controls for details.

polygon

Array

The polygon. See polygon for details.

show-location

Boolean

An indicator of whether to display the current location. When the value is true, the current location is displayed.

include-points

Array

The view is extended on a small scale with the passed coordinates.

Example:

copy
[{    
latitude: 1.350428,    
longitude: 103.861718,
}]

include-padding

Object

The view is displayed within the map padding.

Example:

copy
[{    
   left:0, right:0, 
   top:0, bottom:0
}]

ground-overlays

Array

The overlay, which is a customized texture/image.

Example:

copy
[{
    // Need to change the id when refreshing
    id:'0', 
    // right-top, left-bottom
    'include-points':[{
        latitude: 39.935029,
        longitude: 116.384377,
    },{
        latitude: 39.939577,
        longitude: 116.388331,
    }],
    image:'/image/overlay.png',
    alpha:0.25,
    zIndex:1
}]

tile-overlay

Object

The overlay, which is a grid texture/image.

Example:

copy
{
    url:'http://xxx',
    tileWidth:256,
    tileHeight:256,
    zIndex:1,
}

setting

Object

Settings.

Example:

copy
{
gestureEnable: 1,   
showCompass: 1, 
tiltGesturesEnabled: 1,
}

onMarkerTap

EventHandle

Call this function when clicking on Marker.

Example:

copy
{
markerId,    
latitude,    
longitude, 
}

onCalloutTap

EventHandle

Call this function when the callout corresponding to the Marker is clicked.

Example:

copy
{
markerId, 
latitude, 
longitude, 
}

onControlTap

EventHandle

Call this function when control is clicked.

Example:

copy
{
    controlId
}

onRegionChange

EventHandle

Call this function when the view is changed.

Example:

copy
{
type: "begin/end",
latitude,
longitude,
scale,
skew,
rotate,
causedBy: "update/gesture"
}

onTap 

EventHandle

Call this function when clicking on the map.

Example:

copy
{    
latitude,    
longitude, 
}

mini-scale

Number

Used to limit the minimum zoom level. The value ranges from 3 to 20.

Default value: 3

Note: This parameter is not supported by Apple Maps.

max-scale

Number

Used to limit the maximum zoom level. The value ranges from 3 to 20.

Default value: 20

Note: This parameter is not supported by Apple Maps.

show-compass

Boolean

An indicator of whether to display the compass.

Default value: false

enable-overlooking

Boolean

An indicator of whether to enable the overlook function.

Default value: false

enable-zoom

Boolean

An indicator of whether to enable the zoom function.

Default value: true

enable-scroll

Boolean

An indicator of whether to enable the scrolling function.

Default value: true

enable-rotate

Boolean

An indicator of whether to enable the rotation function.

Default value: false

onInitComplete

Function

Call this function when the map initialization is complete and is going to start rendering the first frame.

markers

Specify a location marker that identifies a location on the map.

Notes:

  • With the markers parameter, multiple location markers can be displayed.
  • The description of the location marker does not support English.

Property

Description

Type

Required

id

The ID of the location marker, when is returned in the click event callback.

Number

Yes

latitude

The latitude of the location.

Value range: -90 - 90

Float

Yes

longitude

The longitude of the location.

Value range: -180 - 180

Float

Yes

title

The name of the location marker.

String

No

iconPath

The image path in the project directory, which cannot be a relative path, but can only be an absolute path beginning with /.

For example: /pages/image/test.jpg

String

Yes

rotate

The angle of clockwise rotation.

Value range: 0 - 360

Default value: 0

Number

No

alpha

The transparency of the image. By default, the value is 1, which means the image is totally opaque. A value of 0 means totally transparent.

Number

No

width

The actual width of the image by default.

Number

No

height

The actual height of the image by default.

Number

No

displayRanges

Indicates to display only at a specific range of the map zoom level.

Sample:

copy
[{
  "from": 10,
  "to": 15
 }]

Array

No

callout

The bubble window in a customized maker. Only one bubble window can be displayed in the map at the same time, which is bond with onCalloutTap.

Sample:

copy
{
    content:"xxx"
}

Object

No

anchorX

The anchorX and anchorY need to appear in pairs, which indicates the anchor point of the marker icon in latitude and longitude:

  • anchorX: The x-axis value. The value ranges from 0 - 1.
  • anchorY: The y-axis value. The value ranges from 0 - 1.

Note: The following pair of values indicates the midpoint of the bottom edge:

  • anchorX: 0.5
  • anchorY: 1

Double

No

anchorY

Double

No

iconAppendStr

This parameter is used together with iconPath. It will generate an image that combines the image corresponding to iconPath and this parameter/string. Then the generated image is used as the icon for the marker.

String

No

iconAppendStrColor

The color of the bottom description text.

Default value: #33B276

String

No

markerLevel

The drawing layer level of the marker on the map, which is unified with the Z-coordinate system of other overlays on the map.

Number

No

label

The bubble on the marker. Multiple bubbles can be displayed on the map at the same time, which is bound with onMarkerTap . See label for details.

Note: this is not supported in Google Maps in iOS.

Sample:

copy
{
    content:"Hello Label",
    color:"#000000",
    fontSize:12,
    borderRadius:"3",
    bgColor:"#ffffff",
    padding:5,
}

Object

No

polygon

Specify a series of coordinates, which form a closed polygon based on the points.

Property

Description

Type

Required

points

An array of latitude and longitude.

Example:

[{

latitude: 0,

longitude: 0

}]

Array

Yes

color

The stroke color. Use hexadecimal numbers to set colors.

Example: #eeeeeeAA

String

No

fillColor

The fill color. Use hexadecimal numbers to set colors.

Example: #eeeeeeAA

String

No

width

The stroke width.

Number

No

displayRanges

Indicates to display only at a specific range of the map zoom level.

Sample:

copy

[{
  "from": 12,
  "to": 17
 }]

Array

No

polyline

Specify a series of coordinates, which are connected from the first item to the last item in an array.

Property

Description

Type

Required

points

An array of latitude and longitude. 

Example:

[{

latitude: 0,

longitude: 0

}]

Array

Yes

color

The stroke color. Use hexadecimal numbers to set colors.

Example: #eeeeeeAA

String

No

width

The stroke width.

Number

No

zIndex

The Z-axis coordinate of the overlay.

Number

No

circles

Display a circle on the map.

Property

Description

Type

Required

latitude

The latitude. The value ranges from -90 to 90.

Float

Yes

longitude

The longitude. The value ranges from -180 to 180.

Float

Yes

color

The stroke color. Use hexadecimal numbers to set colors.

Example: #eeeeeeAA

String

No

fillColor

The fill color. Use hexadecimal numbers to set colors. 

Example: #eeeeeeAA

String

No

radius

The radius in meters. 

Number

Yes

strokeWidth

The stroke width.

Number

No

controls

Used to display controls on the map. The control does not move with the map.

Property

Description

Type

Required

id

The ID of the controll, which is returned in the click event callback.

Number

No

position

The position of the control on the map.

Example:

{

latitude: 0,

longitude: 0

}

Object

Yes

iconPath

The image path in the project directory. It can be a relative path.

Note: Beginning with "/" means the relative path of the mini program root directory.

Example: /pages/image/test.jpg

String

Yes

clickable

An indicator of whether can be clicked.

Default value: false

Boolean

No

Location marker design

label

Property

Required

Note

content

Yes

-

color

No

The default value is #000000.

fontsize

No

The default value is 14.

borderRadius

No

The default value is 20.

bgColor

No

The default value is #FFFFFF.

padding

No

The default value is 10.

FAQs

How do the map components redirect the mini program to the Google Maps for the navigation?

Use the my.openLocation API.

How to obtain the value of scale when the optimize property of the map components is true?

Use the onRegionChange function.

How to create the polygon area on the map manually?

Use the polygon property.

How to modify icons of the first item and the last item in the map components after iconPath is set?

Currently the modification is not supported.

More information

my.createMapContext JSAPI

MapContext Overview