Skip to content

Map Components

Map components are provided by uni-app for displaying maps, supporting various map operations and custom features.

map

The map component is used to display maps, supporting markers, polylines, overlays, and more.

Attributes

AttributeTypeDefaultDescription
longitudeNumberCenter longitude, required
latitudeNumberCenter latitude, required
scaleNumber16Zoom level, range 5-18
markersArrayMarkers
polylineArrayPolylines
circlesArrayCircles
polygonsArrayPolygons
include-pointsArrayZoom view to include all given coordinate points
show-locationBooleanfalseShow current location with direction
enable-3DBooleanfalseShow 3D buildings
show-compassBooleanfalseShow compass
enable-overlookingBooleanfalseEnable overlooking
enable-zoomBooleantrueEnable zoom
enable-scrollBooleantrueEnable drag
enable-rotateBooleanfalseEnable rotation
enable-satelliteBooleanfalseEnable satellite view
enable-trafficBooleanfalseEnable real-time traffic
enable-poiBooleantrueShow POI points
enable-buildingBooleantrueShow buildings

Markers Attributes

AttributeDescriptionTypeRequiredDefault
idMarker IDNumberYes
latitudeLatitudeNumberYes
longitudeLongitudeNumberYes
titleMarker titleStringNo
iconPathIcon pathStringYes
rotateRotation angleNumberNo0
alphaMarker transparencyNumberNo1
widthIcon widthNumberNoActual image width
heightIcon heightNumberNoActual image height
calloutCustom callout above markerObjectNo
labelLabel beside markerObjectNo
anchorAnchor point of marker iconObjectNo

Events

EventDescriptionReturn Value
@markertapTriggered when marker is tappedevent.detail =
@callouttapTriggered when callout is tappedevent.detail =
@controltapTriggered when control is tappedevent.detail =
@regionchangeTriggered when region changesevent.type = begin/end, event.detail =
@tapTriggered when map is tappedevent.detail =
@updatedTriggered when map rendering is updated

Example Code

vue
<template>
  <view class="container">
    <map
      id="myMap"
      :longitude="longitude"
      :latitude="latitude"
      :scale="scale"
      :markers="markers"
      :polyline="polyline"
      :circles="circles"
      :polygons="polygons"
      :include-points="includePoints"
      :show-location="true"
      :enable-3D="false"
      :show-compass="true"
      :enable-zoom="true"
      :enable-scroll="true"
      @markertap="onMarkerTap"
      @callouttap="onCalloutTap"
      @regionchange="onRegionChange"
      @tap="onMapTap"
      style="width: 100%; height: 300px;"
    ></map>
    
    <view class="map-controls">
      <button type="primary" @click="moveToLocation">Move to Current Location</button>
      <button type="primary" @click="addMarker">Add Marker</button>
      <button type="primary" @click="drawRoute">Draw Route</button>
      <button type="primary" @click="includeAllPoints">Show All Points</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // Map center point
      longitude: 116.397390,
      latitude: 39.908860,
      scale: 14,
      
      // Markers
      markers: [{
        id: 1,
        latitude: 39.908860,
        longitude: 116.397390,
        title: 'Tiananmen',
        iconPath: '/static/images/marker.png',
        width: 30,
        height: 30,
        callout: {
          content: 'Tiananmen Square',
          color: '#000000',
          fontSize: 14,
          borderRadius: 4,
          borderWidth: 1,
          borderColor: '#cccccc',
          bgColor: '#ffffff',
          padding: 5,
          display: 'BYCLICK',
          textAlign: 'center'
        },
        label: {
          content: 'Tiananmen',
          color: '#000000',
          fontSize: 12,
          anchorX: 0,
          anchorY: -60,
          borderWidth: 1,
          borderColor: '#ffffff',
          borderRadius: 4,
          bgColor: '#ffffff',
          padding: 2,
          textAlign: 'center'
        }
      }],
      
      // Polylines
      polyline: [],
      
      // Circles
      circles: [{
        latitude: 39.908860,
        longitude: 116.397390,
        color: '#FF0000AA',
        fillColor: '#7cb5ec88',
        radius: 500,
        strokeWidth: 2
      }],
      
      // Polygons
      polygons: [{
        points: [
          {
            latitude: 39.913860,
            longitude: 116.407390
          },
          {
            latitude: 39.913860,
            longitude: 116.387390
          },
          {
            latitude: 39.903860,
            longitude: 116.387390
          },
          {
            latitude: 39.903860,
            longitude: 116.407390
          }
        ],
        strokeWidth: 2,
        strokeColor: '#FF0000AA',
        fillColor: '#7cb5ec88'
      }],
      
      // Include points
      includePoints: [{
        latitude: 39.908860,
        longitude: 116.397390
      }, {
        latitude: 39.913860,
        longitude: 116.407390
      }],
      
      // Map context
      mapContext: null
    }
  },
  onReady() {
    // Get map context
    this.mapContext = uni.createMapContext('myMap', this);
  },
  methods: {
    // Marker tap event
    onMarkerTap(e) {
      console.log('Marker tapped:', e.detail.markerId);
      uni.showToast({
        title: `Marker ${e.detail.markerId} tapped`,
        icon: 'none'
      });
    },
    
    // Callout tap event
    onCalloutTap(e) {
      console.log('Callout tapped:', e.detail.markerId);
      uni.showToast({
        title: `Callout ${e.detail.markerId} tapped`,
        icon: 'none'
      });
    },
    
    // Region change event
    onRegionChange(e) {
      if (e.type === 'end') {
        console.log('Region changed:', e.detail);
      }
    },
    
    // Map tap event
    onMapTap(e) {
      console.log('Map tapped:', e.detail);
    },
    
    // Move to current location
    moveToLocation() {
      this.mapContext.moveToLocation();
      uni.showToast({
        title: 'Moved to current location',
        icon: 'none'
      });
    },
    
    // Add marker
    addMarker() {
      const newMarker = {
        id: this.markers.length + 1,
        latitude: this.latitude + (Math.random() * 0.01 - 0.005),
        longitude: this.longitude + (Math.random() * 0.01 - 0.005),
        title: `Marker ${this.markers.length + 1}`,
        iconPath: '/static/images/marker.png',
        width: 30,
        height: 30
      };
      
      this.markers.push(newMarker);
      
      uni.showToast({
        title: `Marker ${newMarker.id} added`,
        icon: 'none'
      });
    },
    
    // Draw route
    drawRoute() {
      // Simulate route points
      const points = [];
      for (let i = 0; i < 5; i++) {
        points.push({
          latitude: this.latitude + (Math.random() * 0.01 - 0.005),
          longitude: this.longitude + (Math.random() * 0.01 - 0.005)
        });
      }
      
      this.polyline = [{
        points: points,
        color: '#5470c6',
        width: 4,
        dottedLine: false,
        arrowLine: true,
        arrowIconPath: '/static/images/arrow.png'
      }];
      
      uni.showToast({
        title: 'Route drawn',
        icon: 'none'
      });
    },
    
    // Show all points
    includeAllPoints() {
      const points = [];
      
      // Add all markers
      this.markers.forEach(marker => {
        points.push({
          latitude: marker.latitude,
          longitude: marker.longitude
        });
      });
      
      // Add current location
      points.push({
        latitude: this.latitude,
        longitude: this.longitude
      });
      
      this.includePoints = points;
      
      // Use map context to adjust view
      this.mapContext.includePoints({
        points: points,
        padding: [50, 50, 50, 50]
      });
      
      uni.showToast({
        title: 'All points shown',
        icon: 'none'
      });
    }
  }
}
</script>

<style>
.container {
  padding: 15px;
}
.map-controls {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 15px;
}
.map-controls button {
  margin-bottom: 10px;
  width: 48%;
}
</style>

Notes

  1. When using map components, pay attention to platform differences as some features may not be available on specific platforms.

  2. Using map components requires applying for corresponding platform map service keys and configuration:

    • WeChat Mini Program: Configure map service API in WeChat Official Platform
    • App: Configure Amap or Baidu Map AppKey in manifest.json
    • H5: Configure Tencent Map Key in manifest.json
  3. Map components consume significant performance, so use them reasonably and avoid displaying multiple map components on one page simultaneously.

  4. When performing map-related operations, it's recommended to use the mapContext object, which provides more control methods.

  5. Map marker icon paths support both local and network paths, but local paths are recommended for better loading speed.

一次开发,多端部署 - 让跨平台开发更简单