# uni.createMapContext(mapId,this)

Create and return a map context mapContext object. Under the custom component, the second parameter is passed to the component instance this to operate the <map> component inside the component.

Note: uni.createMapContext(mapId, this)

  • app-nvue platform 2.2.5+ supports uni.createMapContext(mapId, this)
  • app-nvue platform 2.2.5- You need to set the component attribute id and ref <map id="map1" ref="map1"></map> at the same time, or use ref directly, such as this.$ refs.map1

Platform Difference Description

App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序、飞书小程序 QQ小程序 快手小程序 京东小程序
1.9.0+

# mapContext

mapContext is bound to a <map> component through mapId, through which the corresponding <map> component can be operated.

List of methods of mapContext object

方法 参数 说明 平台差异说明
getCenterLocation OBJECT 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 uni.openLocation
moveToLocation OBJECT 将地图中心移动到当前定位点,需要配合map组件的show-location使用
translateMarker OBJECT 平移marker,带动画 app-nvue 2.1.5+、微信小程序带动画、抖音、支付宝、京东、百度、QQ小程序
includePoints OBJECT 缩放视野展示所有经纬度 app-nvue 2.1.5+、微信、抖音、支付宝、京东、百度、快手、QQ小程序
getRegion OBJECT 获取当前地图的视野范围
getRotate OBJECT 获取当前地图的旋转角 微信、抖音、支付宝、京东、QQ小程序
getScale OBJECT 获取当前地图的缩放级别
getSkew OBJECT 获取当前地图的倾斜角 微信、抖音、支付宝、京东、QQ小程序
addCustomLayer OBJECT 添加个性化图层 微信小程序
addGroundOverlay OBJECT 创建自定义图片图层,图片会随着地图缩放而缩放 App-nvue 3.1.0+,微信、抖音小程序
addMarkers OBJECT 添加 marker App-nvue 3.1.0+,微信小程序
fromScreenLocation OBJECT 获取屏幕上的点对应的经纬度,坐标原点为地图左上角 微信小程序
initMarkerCluster OBJECT 初始化点聚合的配置,未调用时采用默认配置 App-nvue 3.1.0+,微信小程序
moveAlong OBJECT 沿指定路径移动 marker,用于轨迹回放等场景。动画完成时触发回调事件,若动画进行中,对同一 marker 再次调用 moveAlong 方法,前一次的动画将被打断。支持 android,不支持 autoRotate 属性设置,默认为 ture App-nvue 3.1.0+,微信、抖音小程序
openMapApp OBJECT 拉起地图APP选择导航。 App-nvue 3.1.0+,微信、抖音、快手小程序
removeCustomLayer OBJECT 移除个性化图层 微信小程序
removeGroundOverlay OBJECT 移除自定义图片图层 App-nvue 3.1.0+,微信小程序
removeMarkers OBJECT 移除 marker。 App-nvue 3.1.0+,微信小程序
setCenterOffset OBJECT 设置地图中心点偏移,向后向下为增长,屏幕比例范围(0.25~0.75),默认偏移为[0.5, 0.5] 微信、抖音小程序
toScreenLocation OBJECT 获取经纬度对应的屏幕坐标,坐标原点为地图左上角。 微信小程序
updateGroundOverlay OBJECT 更新自定义图片图层。 App-nvue 3.1.0+,微信、抖音小程序
on Method 监听地图事件。 App-nvue 3.1.0+,微信小程序
$getAppMap 获取原生地图对象 plus.maps.Map App-nvue 1.9.3

Notes on $getAppMap():

  • In pages, must be called in onReady.
  • In components, must be called in mounted.
  • nvue does not have $getAppMap(), please use createMapContext
  • There is no need to provide a placeholder div to use the native map in uni-app, you can use it directly in js after getting $getAppMap().
  • openMapApp iOS is not supported yet, will be added later

OBJECT parameter list of getCenterLocation

Parameter Type Required Description
success Function No Callback function for successful interface call, res = { longitude: "longitude", latitude: "latitude"}
fail Function No Callback function for interface call failure
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

moveToLocation's OBJECT parameter list

Parameter Type Required Description
longitude Number No Longitude, supported by App 2.6.8, H5, JD MiniApp, and WeChat MiniApp 2.8.0+
latitude Number No Latitude, supported by App 2.6.8, H5, JD MiniApp, and WeChat MiniApp 2.8.0+
success Function No Callback function for successful interface call, res = { longitude: "longitude", latitude: "latitude"}
fail Function No The callback function of interface call failure
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

translateMarker's OBJECT parameter list

Parameter Type Required Description
markerId Number Yes Specify marker
destination Object Yes specifies the target point where the marker moves to
autoRotate Boolean Yes Whether to automatically rotate the marker during movement
rotate Number Yes the rotation angle of the marker
moveWithRotate Boolean No Translate and rotate at the same time, the default value is false (only supported by WeChat MiniApp 2.13.0)
duration Number No Animation duration, the default value is 1000ms, translation and rotation are calculated separately
animationEnd Function No Animation end callback function
success Function No Callback function for successful interface call
fail Function No Callback function for interface call failure
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

List of OBJECT parameters for includePoints

Parameter Type Required Description
points Array Yes a list of coordinate points to be displayed in the visible area, [{latitude, longitude}]
padding Array No The distance from the edge of the rectangle formed by the coordinate points to the edge of the map, in pixels. The format is [top, right, bottom, left]. Only the first item of the array can be recognized on Android, and the padding of top, bottom, left, and right is consistent. The developer tools do not currently support the padding parameter.
success Function No Callback function for successful interface call (Alipay MiniApp not support)
fail Function No Callback function for interface call failure (Alipay MiniApp not support)
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails) (Alipay MiniApp not support)

OBJECT parameter list of getRegion

Parameter Type Required Description
success Function No Callback function for successful interface call, res = {southwest, northeast}, latitude and longitude of the southwest and northeast corners
fail Function No Callback function for interface call failure (Alipay MiniApp not support)
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails) (Alipay MiniApp not support)

OBJECT parameter list of getRotate

Parameter Type Required Description
success Function No Callback function for successful interface call, res = {rotate}, rotation angle
fail Function No Callback function for interface call failure (Alipay MiniApp not support)
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails) (Alipay MiniApp not support)

OBJECT parameter list for getScale

Parameter Type Required Description
success Function No Callback function for successful interface call, res = {scale}, scaling value
fail Function No Callback function for interface call failure (Alipay MiniApp not support)
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails) (Alipay MiniApp not support)

OBJECT parameter list for getSkew

Parameter Type Required Description
success Function No Callback function for successful interface call, res = {skew}, skew angle
fail Function No Callback function for interface call failure (Alipay MiniApp not support)
complete Function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails) (Alipay MiniApp not support)

addCustomLayer's OBJECT parameter list

Property Type Default Value Required Description
layerId string yes personalized layer id
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

AddGroundOverlay's OBJECT parameter list

Property Type Default Value Required Description
id String Yes image layer id
src String Yes Image path, support network image, temporary path, code package path
bounds Object Yes the range of latitude and longitude covered by the image
visible Boolean true No Visible
zIndex Number 1 No Layer drawing order
opacity Number 1 No Layer transparency
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

Structure of object.bounds

Property Type Default Value Required Description
southwest Object Yes the latitude and longitude of the southwest corner
northeast Object Yes the latitude and longitude of the northeast corner

Structure of southwest

Property Type Default Value Required Description
longitude number Yes longitude
latitude number Yes latitude

Structure of northeast

Property Type Default Value Required Description
longitude number Yes longitude
latitude number Yes latitude

addMarkers OBJECT parameter list

Property Type Default Value Required Description
markers Array Yes same as the marker attribute passed in the map component
clear boolean false No Whether to clear all markers on the map first
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

removeMarkers OBJECT parameter list

Property Type Default Value Required Description
markerIds Array Yes an array composed of the id attributes of the markers to be deleted
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

moveAlong's OBJECT parameter list

Property Type Default Value Required Description
markerId Number Yes Specify marker
path Array Yes the coordinate string of the movement path, and the coordinate point format is {longitude, latitude}
autoRotate boolean true No Automatically change the rotation angle of the marker according to the path direction
duration number Yes time for smooth movement
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

openMapApp's OBJECT parameter list

Property Type Default Value Required Description
longitude Number Yes destination longitude
latitude Number Yes Destination Latitude
destination String Yes destination name
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

List of OBJECT parameters for setLocMarkerIcon@setLocMarkerIcon

Property Type Default Value Required Description
iconPath string No Icon path, support network path, local path, code package path
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

App nvue 3.6.9+ support

mapContext (App platform map service provider difference)

Properties Description Whether AutoNavi supports Whether Google Maps supports
setLocMarkerIcon Set locator icon, support network path, local path, code package path supported not supported
moveAlong Move the marker along the specified path, used for track playback and other scenarios Supported (autoRotate attribute is not supported) Supported
addCustomLayer Add custom layer Not supported Not supported
removeVisualLayer remove visual layer not supported not supported
fromScreenLocation Get the latitude and longitude corresponding to the point on the screen, the coordinate origin is the upper left corner of the map Not supported Not supported
removeCustomLayer remove custom layer not supported not supported
setCenterOffset Set the offset of the center point of the map, backward and downward for growth, screen scale range (0.25~0.75) Not supported Not supported
toScreenLocation Get the screen coordinates corresponding to the latitude and longitude. The origin of the coordinates is the upper left corner of the map. Not Supported Not Supported

MapContext.on() (app-nvue, WeChat MiniApp support)

markerClusterCreate Triggered when zooming or dragging causes a new cluster to be generated, and only returns information about the newly created cluster.

return parameter

Parameter Type Description
clusters Array&lt;ClusterInfo&gt; Aggregated cluster data

markerClusterClick Cluster click event.

return parameter

Parameter Type Description
cluster ClusterInfo Aggregated cluster

ClusterInfo structure

Parameter Type Description
clusterId Number The id of the aggregation cluster
center LatLng the coordinates of the cluster
markerIds Array&lt;Number&gt; Array of point marker data in the cluster

initMarkerCluster(OBJECT) structure

Property Type Default Value Required Description
enableDefaultStyle boolean true no enable default aggregation style
zoomOnClick boolean true No Whether to achieve aggregation and separation when clicking on an already aggregated marker
gridSize boolean 60 No Aggregatable distance of the aggregation algorithm, that is, points whose distance is less than this value will be aggregated together, in pixels
success function No Callback function for successful interface call
fail function No Callback function for interface call failure
complete function No The callback function for the end of the interface call (it will be executed when the call succeeds or fails)

sample code

  MapContext.on('markerClusterCreate', (res) => {})
  MapContext.on('markerClusterClick', (res) => {})

Map aggregation API example (nvue)

Zoom out the map to see that multiple markers are merged into one and display the aggregated number, and restore after zooming in on the map

<template>
  <view class="content">
    <map id="map" class="map" :show-location="true" :latitude="latitude" :longitude="longitude"></map>
  </view>
</template>

<script>
  const img = '/static/logo.png';

  export default {
    data() {
      return {
        latitude: 23.099994,
        longitude: 113.324520,
      }
    },
    onReady() {
      this._mapContext = uni.createMapContext("map", this);

      // only calls initialization, will trigger on.("markerClusterCreate", (e) => {})
      this._mapContext.initMarkerCluster({
        enableDefaultStyle: false,
        zoomOnClick: true,
        gridSize: 60,
        complete(res) {
          console.log('initMarkerCluster', res)
        }
      });

      this._mapContext.on("markerClusterCreate", (e) => {
        console.log("markerClusterCreate", e);
      });

      this.addMarkers();
    },
    methods: {
      addMarkers() {
        const positions = [
          {
            latitude: 23.099994,
            longitude: 113.324520,
          }, {
            latitude: 23.099994,
            longitude: 113.322520,
          }, {
            latitude: 23.099994,
            longitude: 113.326520,
          }, {
            latitude: 23.096994,
            longitude: 113.329520,
          }
        ]

        const markers = []

        positions.forEach((p, i) => {
          console.log(i)
          markers.push(
            Object.assign({},{
              id: i + 1,
              iconPath: img,
              width: 50,
              height: 50,
              joinCluster: true, // 指定了该参数才会参与聚合
              label: {
                  width: 50,
                  height: 30,
                  borderWidth: 1,
                  borderRadius: 10,
                  bgColor: '#ffffff',
                  content: `label ${i + 1}`
              }
            },p)
          )
        })
        this._mapContext.addMarkers({
            markers,
            clear: false,
            complete(res) {
              console.log('addMarkers', res)
            }
        })
      }
    }
  }
</script>

<style>
  .content {
    flex: 1;
  }

  .map {
    flex: 1;
  }
</style>

# mapSearch 模块(仅app-nvue支持,Google地图不支持)

# reverseGeocode(Object,callback);

Reverse Geocoding

# Object
Attribute Type Default Required Description
point Object Yes {latitude: latitude, longitude: longitude}
# callback returns Object parameter description
property type description
type String "success" means success, "fail" means failure
code Number returns 0 for success, and returns the corresponding code for failure
message String Failure description
address String Address after query (returned when successful)

# poiSearchNearBy(Object,callback);

Surrounding search

# Object
Attribute Type Default Required Description
point Object Yes the coordinates of the retrieved center point {latitude: latitude, longitude: longitude}
key String Yes search key
radius Number 3000 No The retrieved radius, in meters
index Number 1 No The page number index of the search result to be obtained
offset Number 10 No Set the number of entries per page (10 entries per page by default). HBuilder 3.2.13+
# callback returns Object parameter description
property type description
type String "success" means success, "fail" means failure
code Number returns 0 for success, and returns the corresponding code for failure
message String Failure description
totalNumber Number The number of POIs returned
currentNumber Number Number of POIs on the current page
pageNumber Number number of pages
pageIndex Number Current page number index
poiList Array.<poiObject> POI information array
# poiObject
property type description
location Object {latitude: latitude, longitude: longitude}
name String name
type String Type
distance Number distance (in meters)
address String address

# poiKeywordsSearch(Object,callback);

Keyword search

# Object
Attribute Type Default Required Description
key String Yes search key
index Number 1 No To get the page number index of the search results (10 data per page)
city String No Query the city, optional values: cityname (Chinese or Chinese spelling), citycode, adcode.code reference table
types String No type, multiple types are separated by "|" Optional values: text classification, classification code code reference table
point Object No After setting, the returned results will be sorted according to the distance from this point {latitude: latitude, longitude: longitude}
sortrule Number 0 No Sorting rules, 0-distance sorting; 1-comprehensive sorting, default 0
offset Number 10 No Set the number of entries per page (10 entries per page by default). HBuilder 3.2.13+
cityLimit Boolean false No Mandatory city limit function Default false, for example: search for Tiananmen Square in Shanghai, if citylimit is true, it will not return POIs related to Tiananmen Square in Beijing. HBuilder 3.2.13+
# callback returns Object parameter description
property type description
type String "success" means success, "fail" means failure
code Number returns 0 for success, and returns the corresponding code for failure
message String Failure description
totalNumber Number The number of POIs returned
currentNumber Number Number of POIs on the current page
pageNumber Number number of pages
pageIndex Number Current page number index
poiList Array.<poiObject> POI information array

Tips

  • App side uses map, nvue is more powerful than vue, and there is no hierarchical problem.
  • The vue page on the App side defaults to Gaode map, and Baidu map can also be selected. But app-nvue only has Gaode map, not Baidu map. And the map selection api (mapSearch), only supports Gaode map.
  • The H5 terminal needs to be deployed on the https service to obtain location information, and the local preview (localhost) can still use the http protocol.
  • When a PC device without a GPS module uses the Chrome browser, the location information is obtained by connecting to the Google server, and domestic users may fail to obtain the location information.
  • To use the map component on the app side, you need to apply for SDK qualification from a third-party service provider such as AutoNavi or Baidu, and obtain an AppKey. When packaging, you need to fill in the Appkey in the SDK configuration of the manifest. There are detailed application guidelines on the manifest visual interface, see: https://ask.dcloud.net.cn/article/29
  • The use of maps on the H5 side is related to positioning. It is necessary to configure the secret key applied by a third-party map service provider such as Tencent or Google in manifest.json ( key).
  • The <map> component defaults to the coordinates of the National Survey Bureau. When calling uni.getLocation to pass the returned result to the <map> component, you need to specify the type as gcj02.

# Three-party positioning and map service fee description

使用三方定位或者地图服务,需向服务提供商(如:高德地图、百度地图、腾讯地图、谷歌地图)申请商业授权和缴纳费用(5万/年)。

DCloud为开发者争取了福利,可优惠获取高德、腾讯的商业授权。如有需求请发邮件到bd@dcloud.io(注明你的公司名称、应用介绍、HBuilder账户);你也可以直接通过uni-im发起在线咨询,在线咨询地址:DCloud地图服务专员

详见:https://uniapp.dcloud.net.cn/tutorial/app-geolocation.html#lic